When i go to dashboard route i want to show my hamburger icon [duplicate] - react-router-dom

I am having trouble writing code to render a login page with no navbar and sidebar. I have come across some pages that ask similar questions but none seem to pertain to my current situation.
How to hide navbar in login page in react router
the example given is great but I believe the way of accomplishing that same task has changed with react-router-dom v6 leading me to read about this change in https://dev.to/iamandrewluca/private-route-in-react-router-v6-lg5
It seems I am not understanding a certain aspect about routing with React Router. In the code below I have two Routes. One of the routes(Login) I would like to have render without the NavBar and SideBar component.
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
</Routes>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Routes>
<Route path="/" element={<Dashboard />} />
</Routes>
</div>
</main>
</>
);
};
An alternative, that I also tried, would be to move the NavBar and SideBar tags into the Dashboard component, but then I would essentially have to do the same copy and paste for any new components. This method felt wrong and inefficient , but if this is the correct way of doing it I will do the needful
Edit: I think it's important to include what it currently does is load the Login page with the NavBar and SideBar included. Navigating to the dashboard component has the NavBar and SideBar but this is intended.
What I would like is for the Login page not to have the NavBar and SideBar

If I understand your question, you are wanting to render the nav and sidebar on the non-login route. For this you can create a layout component that renders them and an outlet for the nested routes.
Using nested routes
import { Outlet } from 'react-router-dom';
const AppLayout = () => (
<>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Outlet /> // <-- nested routes rendered here
</div>
</main>
</>
);
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<AppLayout />} >
<Route path="/" element={<Dashboard />} /> // <-- nested routes
</Route>
</Routes>
</>
);
};
Using a routes configuration and useRoutes hook
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { useRoutes } from 'react-router-dom';
const App = () => {
const routes = useRoutes(routesConfig);
return routes;
};
Using a routes configuration and data routers (introduced in v6.4.0)
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter(routesConfig);
const App = () => {
return <RouterProvider router={router} />;
};

The easiest way for you to hide the navbar would be to go to the login page component and call useLocation(). Then you woulf do something like this after declaring the use location. And assigning it to a variable location
{ location.pathname === "/login" ? null : (
Render the whole navbar component);
Not sute if you can be able to read as I type from my phone

Related

What is wrong with my pagination in my react app? (with semantic ui)

So I am making a react app with semantic ui, that communicates with my own backend and displays news. I want to use pagination, that I tried to make it like it is said in this article: https://www.codementor.io/#maseh87/paginating-a-react-app-with-semantic-ui-x1g4a0t79
So here is my app.tsx:
import { Component } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import Navbar from "./components/navbar/Navbar";
import MainPage from "./pages/MainPage";
import NewsDetailPage from "./pages/NewsDetailPage";
interface AppProps {}
interface AppState {}
class App extends Component<AppProps, AppState> {
render() {
return (
<div>
<header>
<Navbar />
</header>
<div className="ui container" style={{paddingBottom: "2rem"}}>
<Routes>
<Route path="/news/:id" element={<NewsDetailPage />} />
<Route path="/news" element={<MainPage />} />
<Route path="*" element={<Navigate to="/news" replace />} />
</Routes>
</div>
</div>
);
}
}
export default App;
And my main page, this includes the pagination:
import { useEffect, useState } from "react";
import NewsList from "../components/news list/NewList";
import { NewsModel } from "../models/news.model";
import { newsService } from "../services/news.service";
import MainNews from "../components/main news/MainNews";
import { Pagination } from 'semantic-ui-react';
const MainPage = () => {
const [news, setNews] = useState<NewsModel[]>([]);
const [activePage, setActivePage] = useState(1);
const [apiUrl, setApiUrl] = useState('http://localhost:3001/api/');
useEffect(() => {
const fetchNews = async () => {
setNews(await newsService.getNews());
};
fetchNews();
}, []);
const [main, ...rest] = news;
const onChange = (pageInfo: any) => {
setActivePage(pageInfo.activePage);
setApiUrl('http://localhost:3001/api/?page=' + activePage.toString());
};
return (
<div>
<MainNews main={main} />
<NewsList news={rest} />
<Pagination
activePage={activePage}
onPageChange={onChange}
totalPages={10}
ellipsisItem={null}
/>
</div>
);
};
export default MainPage;
So I want to display the first piece of news with a different style and then the list of remaining news. But I also want this on only the first page, on the rest I just want to see the list.
But what is wrong with the pagination things? It displays the numbers of the pages, but nothing happens when I click on the next page.

react router dom 6^. Unable to route Dynamically

I am having trouble with dynamic routing in
react-router-dom.
Whenever I go to the dynamic page I get a white screen. Only error message is
The resource from localhost:8082/individuals/bundle.js was blocked due to MIME type(“text/html”) mismatch (X-Content-Type-Options: nosniff).
I have research countless articles and have been unable to find a solution.
Every Other static Component Works and is able to pull from the api.
The API I am pulling from is able to dynamically display products.
"http://localhost/40"
will display the object with the id of 40 in json format. Node.js express Api
Thank you for your time
Route Component
function Rout(){
return(
<div>
<BrowserRouter>
<Menu/>
<div className="page">
<Routes>
<Route index element={<MainContent />} />
<Route path="/products" element={<Product />} />
<Route path='/individuals/:id' element={<Individualproduct />} />
<Route path="/about/" exact element={<About />} />
<Route path="/shippingandreturns" element={<Shipping />} />
</Routes>
</div>
</BrowserRouter>
</div>
)
}
export default Rout
Dynamic Component
const Individualproduct = () => {
const { id } = useParams();
const [products, setProducts] = useState([]);
const url = 'http://192.168.1.91:4001/';
useEffect(()=>{
async function getProduct(){
const response = await axios.get(`${url}/${id}`);
const a = (response.data.Results)
console.log(a)
setProducts(a)
}
getProduct()
}, [])
return (
<article>
{
products.map((item)=>{
<h1>{item.id}</h1>
})
}
</article>
);
};

application 'react app1' died in status LOADING_SOURCE_CODE: [qiankun]: Target container with #react-app1 not existed while react app1 loading

I am using Qiankun as a micro-frontend-servlet and need someone, who has a bit of knowledge around that tool, who can help me with the following problem:
My Master-Application, as well as all Micro-Applications run on a react-app, which have been created via "npx create-react-app".
It seems to me, that the routes defined in the -Component seem to work once. To be specific:
If i click on one -Component redirecting the browser to "/react-app" , this works just fine. If i then, and that is the crucial part of that whole problem, click on the other link, to the other micro-application. The whole page goes blank and in the web-console you'll find the following error:
Uncaught Error: application 'react app1' died in status LOADING_SOURCE_CODE: [qiankun]: Target container with #react-app1 not existed while react app1 loading!
There's an FAQ-section on the site just covering this issue, but i can't wrap my head around that on how it is done the proper way.
Qiankun-FAQ's
Master-Application:
(...)
function App(props) {
registerMicroApps([
{
name: "react app", // app name registered
entry: "//localhost:3001",
container: "#react-app",
activeRule: "/react-app",
},
{
name: "react app1", // app name registered
entry: "//localhost:3002",
container: "#react-app1",
activeRule: "/react-app1",
},
]);
start()
return (
<div className="App">
{/* <div id="react-app"></div> */}
<Header></Header>
<Router>
<Switch>
<Route exact path="/"></Route>
<Route exact path="/react-app">
<div id="react-app"></div>
</Route>
<Route exact path="/react-app1">
<div id="react-app1"></div>
</Route>
</Switch>
</Router>
</div>
);
}
export default App;
(...)
Header-Component, having the Main-Routes configured:
const Header = (props) => {
return (
<div className={Styles.Header}>
<img alt="Avocodo Logo" src={Logo}></img>
<h1>Main Application</h1>
<BrowserRouter /*basename={window.__POWERED_BY_QIANKUN__ ? '/react-app' : '/'}*/>
<Link to="/react-app">Sub-App</Link>
<Link to="/react-app1">Sub-App1</Link>
</BrowserRouter>
</div>
);
};
export default Header;
One of the two identical Micro-Applications:
import React from 'react'
import { BrowserRouter } from 'react-router-dom'
import './App.css';
function App() {
return (
<div className="App">
<BrowserRouter basename={window.__POWERED_BY_QIANKUN__ ? '/react-app1' : '/'}>
<h2>Sub-App2</h2>
</BrowserRouter>
</div>
);
}
export default App;
Has anyone ever worked w/Qiankun and can help me on how to get the issue solved?
Thankful for any hints!
<Route exact path="/"></Route>
<Route exact path="/react-app">
<div id="react-app"></div>
</Route>
<Route exact path="/react-app1">
<div id="react-app1"></div>
</Route>
the divs with IDs "react-app" and "react-app1" should be kept outside the switch tag. They need to be available when the micro-app is being registered.
But in your case, the div is available only if the route is selected. So before you navigate another route, qiankun tries to register the micro-app to the dom element, which has not been added yet.

Reactjs - Move to next page after login

I'm new to react and I'm trying to make a small program.
I have a react based client, my server is running on Nodejs and my db is Postgres.
I managed to make a working login from the client with auth from the server.
How can I show a new page after a login has been successful?
my app.js:
export default class App extends React.Component {
render() {
const { url } = this.props.match
return (
<div className="fx-row high">
<Sidebar url={ url }/>
<div className="page fx-col fx-grow" style = {{ width : 150, height : 150, marginLeft : 450, marginTop : 100}}>
<Switch>
<Route path={ url + 'demo' } component={ Demo }/>
<Route path={ url + 'audits' } component={ Audits }/>
<Route component={ Login }/>
</Switch>
</div>
</div>
)
}
}
In My login I have a handleSubmit which sends a post with parameters to the server and get the response body.
I want that after handltSubmit get the correct response, to show a different screen from the login, lets say just a screen that says "You are logged in" for now.
Thank you
Use BrowserRouter from react-router-dom.
import {BrowserRouter, Switch, Route} from 'react-router-dom';
export default class App extends React.Component {
render() {
return (
<div className="fx-row high">
<Sidebar url={ url }/>
<div className="page fx-col fx-grow" style = {{ width : 150, height : 150, marginLeft : 450, marginTop : 100}}>
<BrowserRouter>
<Switch>
<Route path='/demo' component={ Demo }/>
<Route path='/audit' component={ Audits }/>
<Route path='/SiteMange' component={ SiteManage }/>
<Route path='/' component={ Login }/>
</Switch>
</BrowserRouter>
</div>
</div>
)
}
}
In your Login component you can call push method of history object that you will get as props in your routed page.
so on login success call the following method to redirect to your next route. For example say home page.
this.props.history.push('SiteMange')
Assuming you're using fetch for server request you could do the following:
handleSubmit = () => {
fetch(your code here)
.then(res => res.json())
.then(data => {
if ( data.user ) {
this.props.history.push("home"); // in this case I use home as your path name
} else {
Some actions here
}
});
};
Hope it helps.

Child route handled by the same parent's component using react router

I'm trying to define the routes for a paginated application.
/ -> handled by App
/page/:page -> also handled by App
These are what my routes look like:
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="paginated" path="page/:page" handler={App} />
</Route>
);
This is what App looks like:
var App = React.createClass({
render : function() {
return (
<div>
<RouteHandler/>
Something...
</div>
);
}
});
The problem here is that, as paginated is an app's child route, that Something... in the componet gets rendered twice.
What I'm trying to acomplish here is to default to page 1 for the app route and to load the desired page for the paginated route, without loading twice.
Any way to do this?
Using the App handler twice works the way you expect - it calls Apptwice. However, the parent should only be used as the parentRoute Handler, and the children use their ownHandlers`.
To get the initial page to load properly, use a DefaultRoute for the base path:
routes
var routes = (
<Route name="app" path="/" handler={App}>
<DefaultRoute handler={Home}/>
<Route name="paginated" path="page/:page" handler={Page} />
</Route>
);
app
var App = React.createClass({
render : function() {
return (
<div>
<RouteHandler/>
</div>
);
}
});
home
var Home = React.createClass({
render : function() {
return (
<div>
...Something...
</div>
);
}
});
page
var Page = React.createClass({
render : function() {
return (
<div>
...Something Completely Different...
</div>
);
}
});
The React Router Default Handler Docs have a more substantial example:
<Route path="/" handler={App}>
<!--
When the url is `/`, this route will be active. In other
words, `Home` will be the `<RouteHandler/>` in `App`.
-->
<DefaultRoute handler={Home}/>
<Route name="about" handler={About}/>
<Route name="users" handler={Users}>
<Route name="user" handler={User} path="/user/:id"/>
<!-- when the url is `/users`, this will be active -->
<DefaultRoute name="users-index" handler={UsersIndex}/>
</Route>
</Route>
Notice here that <Route name="user" handler={User} path="/user/:id"/> also has a default route, so when there is no :id match it has somewhere to go.
Hope this helps!
At the end I came up with a solution using a redirection that allowed me to have the pagination and nested routes in the paginated one.
var routes = (
<Route name="app" path="/" handler={App}>
<Redirect from="/" to="paginated" params={{ page : 1 }} />
<Route name="paginated" path="page/:page" handler={PaginationLoader} />
</Route>
);

Resources