React Router with other components - javascript

I have one problem that I can not understand. I am totally a beginner in ReactJS so I hope you will help me. I made Navigation with React Router and it works, but when I start to render all other components in App.js nothings happened. When I am routing through the navigation bar it is rendering, but on scroll, nothing happened.
This is my App.js without rendering other components that work normally, but when I add something like , it is the same without scroll.
my code :
const App = () => {
return (
<div>
<Router>
<Topbar />
<About />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/service" component={Service} />
<Route path="/portfolio" component={Portfolio} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
</div>
);
};
export default App;

You need to use a redirect
1/ import {Redirect} from 'react-router-dom';
2/ Change your Home route to <Route exact path="/home" component={Home} />
3/ Add the redirect (It must be the last route)
<Route exact path="/">
<Redirect to="/home" />
</Route>
Example :
import React from 'react';
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from 'react-router-dom';
import Home from './Home';
import About from './About';
import Service from './Service';
import Portfolio from './Portfolio';
import Contact from './Contact';
const App = () => {
return (
<Router>
<Switch>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/service" component={Service} />
<Route path="/portfolio" component={Portfolio} />
<Route path="/contact" component={Contact} />
{/* Redirect */}
<Route exact path="/">
<Redirect to="/home" />
</Route>
</Switch>
</Router>
);
};
export default App;
If you want to check a demo : Stackblitz

Related

React Router v6 : How to render multiple component inside and outside a div with the same path

I'm trying to upgrade to react-router-dom v6 :
v5
In version 5 it works like a charm:
App.js
import Sidebar from "./components/sidebar/Sidebar";
import Topbar from "./components/topbar/Topbar";
import "./app.css";
import Home from "./pages/home/Home";
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
import UserList from "./pages/userList/UserList";
import User from "./pages/user/User";
import NewUser from "./pages/newUser/NewUser";
import ProductList from "./pages/productList/ProductList";
import Product from "./pages/product/Product";
import NewProduct from "./pages/newProduct/NewProduct";
import Login from "./pages/login/Login";
function App() {
const admin = JSON.parse(JSON.parse(localStorage.getItem("persist:root"))?.user || "{}")?.currentUser?.isAdmin ;
return (
<Router>
<Switch>
<Route path="/login">
<Login />
</Route>
{admin && (
<>
<Topbar />
<div className="container">
<Sidebar />
<Route exact path="/">
<Home />
</Route>
<Route path="/users">
<UserList />
</Route>
<Route path="/user/:userId">
<User />
</Route>
<Route path="/newUser">
<NewUser />
</Route>
<Route path="/products">
<ProductList />
</Route>
<Route path="/product/:productId">
<Product />
</Route>
<Route path="/newproduct">
<NewProduct />
</Route>
</div>
</>
)}
</Switch>
</Router>
);
}
export default App;
v6
When upgraded to v6 I changed my code to be like this:
<Routes>
<Route path="/login" element={<Login />} />
{admin && (
<>
<Route path="/" element={<Topbar />}/>
<Route path="/" element={
<>
<div className="container">
<Route index element={<Sidebar/>}/>
<Route index element={<Home/>}/>
<Route path="/users" element={<UserList />} />
<Route path="/user/:userId" element={<User />} />
<Route path="/newUser" element={<NewUser />} />
<Route path="/productList" element={<ProductList />} />
<Route path="/product/:productId" element={<Product />} />
<Route path="/newProduct" element={<NewProduct />} />
</div>
</>
}
</>
)}
</Routes>
This is my css file for App.js
Notice: the Topbar component should be outside the div, and react router didn't recognize the components inside the as routes even without div, that means each component should have a unique path, I tried also two components with the same path like this:
<Route path="/" element = {<><Home/><Sidebar/><>}, but the css is not taking effect
.container {
display: flex;
margin-top: 50px;
}
It doesn't work. I tried different code and I searched a lot without finding any solution.
Part of the issue is that you are rendering multiple identical paths, i.e. two "/" paths and two nested index paths. This won't work.
In react-router-dom v6 you can create what are called layout components. The layout components can render your headers and footers, sidebars, drawers, and general content layout elements, and importantly an Outlet component for the nested/wrapped Route components to be rendered into.
Example:
import { Outlet } from 'react-router-dom';
const AppLayout = ({ admin }) => admin ? (
<>
<Topbar />
<div className="container">
<Sidebar />
<Outlet />
</div>
</>
) : null;
Render the layout component into a Route wrapping the routes you want to be rendered into the specific layout.
<Routes>
<Route path="/login" element={<Login/>} />
<Route element={<AppLayout admin={admin} />}>
<Route index element={<Home />} />
<Route path="/users" element={<UserList />} />
<Route path="/user/:userId" element={<User />} />
<Route path="/newUser" element={<NewUser />} />
<Route path="/productList" element={<ProductList />} />
<Route path="/product/:productId" element={<Product />} />
<Route path="/newProduct" element={<NewProduct />} />
</Route>
</Routes>
I will share working code from my project, hope this will help you.
Try to create a component layout that should look something like this:
// Layout.js
import React from "react";
import { NavBar } from "./SidebarNav";
export const Layout = ({ children }) => {
return (
<>
<div className="block">
<NavBar />
<div className="w-full ">{children}</div>
</div>
</>
);
};
and then create routes in a similar way:
// routes.js
import { Routes, Route } from "react-router-dom";
import { Layout } from "./layout/Layout";
import Home from "./pages/Home";
import { ItemList } from "./pages/ItemList";
const BaseRouter = () => (
<>
<Layout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/item-list/" element={<ItemList />} />
</Routes>
</Layout>
</>
);
export default BaseRouter;
Splitting routes into a separate file gives you more freedom and, above all, makes your code more accessible.
// App.js
import { BrowserRouter as Router } from "react-router-dom";
import BaseRouter from "./routes";
function App() {
return (
<Router>
<BaseRouter />
</Router>
);
}
export default App;

Routing To another page is not happening without refreshing after clicking on the link in React

I have one Navbar in React with the following code
import './App.css';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
import Header from './components/header/Header';
import Home from './components/home/Home';
import About from './components/about/About';
import Accessories from './components/accessories/Accessories';
import Category1 from './components/accessories/categories/Category1';
import Category2 from './components/accessories/categories/Category2';
import Category3 from './components/accessories/categories/Category3';
import Category4 from './components/accessories/categories/Category4';
import Contact from './components/contact/Contact';
import Footer from './components/footer/Footer';
const App = () => {
return (
<div className="App">
<Header />
<Router>
<Switch>
<Route exact path="/">
<Home />
<About />
<Accessories />
<Contact />
</Route>
<Route exact path="/category1">
<Category1 />
</Route>
<Route exact path="/category2">
<Category2 />
</Route>
<Route exact path="/category3">
<Category3 />
</Route>
<Route exact path="/category4">
<Category4 />
</Route>
</Switch>
</Router>
<Footer />
</div>
);
}
export default App;
I can go smoothly from / to /category1, but when I reroute to / from /category1, no rerendering is happening until I refresh the page.
I have no idea what to do now. Thank you for any help in advance
Edited: I just changes all my Links to anchor tags and now they are working but is it a good practice?
<Route exact path="/">
<Home />
<About />
<Accessories />
<Contact />
</Route>
Put the above code after all the routes are being defined and it should work
<Switch>
<Route exact path="/category1">
<Category1 />
</Route>
<Route exact path="/category2">
<Category2 />
</Route>
<Route exact path="/category3">
<Category3 />
</Route>
<Route exact path="/category4">
<Category4 />
</Route>
<Route exact path="/">
<Home />
<About />
<Accessories />
<Contact />
</Route>
</Switch>
The '/' path should be defined at the last after all the paths have been defined
You have to use the element to redirect to other routes. In "/category1", you can use the element to redirect "/" without reloading the page.

React Routes are not working properly the URl changes but its rendering the one same page on any link i click ,

whenever i click on any link, it changes the URL but its show's me only one page."Job Category"
import App from "./App";
import User from "./components/UserManagment/Users";
import Agents from "./components/UserManagment/Agents";
import Usertable from "./components/Usertable";
import Usertopbar from "./components/Usertopbar";
import { Switch, Route } from "react-router-dom";
import UserRole from "./components/UserManagment/UserRole";
import Suppliers from "./components/Contact/Suppliers";
import Group from "./components/Contact/Group";
import Mod from "./components/Model";
import Custom from "./components/Contact/Custom";
import Contactmodel from "./components/Contact/Contactmodel";
import Login from "./components/Rm.live/Login";
import Signup from "./components/Rm.live/Signup";
import Rmtable from "./components/Rm.live/rm/Rmtable";
import Blogin from "./components/Bootstrap/Login";
import RmSkills from "./components/Rm.live/rm/RmSkills";
export const Routes = () => {
return (
<>
<Switch>
<Route path="/" component={App} exact />
<Route path="/agents" component={Agents} exact />
<Route patch="/rmskills" component={RmSkills} exact />
<Route patch="/rmtable" component={Rmtable} exact />
<Route path="/Blogin" component={Blogin} exact />
<Route path="/login" component={Login} />
<Route path="/signup" component={Signup} />
<Route path="/user" component={User} exact />
<Route path="/userrole" component={UserRole} exact />
<Route path="/usertable" component={Usertable} exact />
<Route path="/usertopbar" component={Usertopbar} exact />
<Route path="/mod" component={Mod} exact />
<Route Path="/custom" component={Custom} />
<Route path="/group" component={Group} exact />
<Route Path="/contactmodel" component={Contactmodel} />
<Route path="/suppliers" component={Suppliers} exact />
</Switch>
</>
);
};
export default Routes;
when ever i click on any of the link it show me " Job category " page
enter image description here
Wrap your switch inside the browser router. More over re arrange your routes as react will render the first matching route.
import App from "./App";
import User from "./components/UserManagment/Users";
import Agents from "./components/UserManagment/Agents";
import Usertable from "./components/Usertable";
import Usertopbar from "./components/Usertopbar";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import UserRole from "./components/UserManagment/UserRole";
import Suppliers from "./components/Contact/Suppliers";
import Group from "./components/Contact/Group";
import Mod from "./components/Model";
import Custom from "./components/Contact/Custom";
import Contactmodel from "./components/Contact/Contactmodel";
import Login from "./components/Rm.live/Login";
import Signup from "./components/Rm.live/Signup";
import Rmtable from "./components/Rm.live/rm/Rmtable";
import Blogin from "./components/Bootstrap/Login";
import RmSkills from "./components/Rm.live/rm/RmSkills";
export const Routes = () => {
return (
<>
<BrowserRouter basename={process.env.PUBLIC_URL}>
<Switch>
<Route path="/agents" component={Agents} exact />
<Route patch="/rmskills" component={RmSkills} exact />
<Route patch="/rmtable" component={Rmtable} exact />
<Route path="/Blogin" component={Blogin} exact />
<Route path="/login" component={Login} />
<Route path="/signup" component={Signup} />
<Route path="/user" component={User} exact />
<Route path="/userrole" component={UserRole} exact />
<Route path="/usertable" component={Usertable} exact />
<Route path="/usertopbar" component={Usertopbar} exact />
<Route path="/mod" component={Mod} exact />
<Route Path="/custom" component={Custom} />
<Route path="/group" component={Group} exact />
<Route Path="/contactmodel" component={Contactmodel} />
<Route path="/suppliers" component={Suppliers} exact />
<Route path="/" component={App} exact />
</Switch>
</BrowserRouter>
</>
);
};
export default Routes;

React router always display at the bottom the Error page

I'm having a problem regarding using of error page in my react app. The 404 page always shows at the bottom of every page that I render. I'm new to react. I hope someone can help me.
This is my App.js
import {BrowserRouter as Router,Switch,Route} from 'react-router-dom';
import Login from './components/auth/Login';
import Register from './components/auth/Register';
import ErrorPage from './components/ErrorPage';
import Order from './components/Order';
import Navbar from './components/partials/Navbar';
import Footer from './components/partials/Footer';
import Shop from './components/Shop';
import ItemDetails from './components/ItemDetails';
import Cart from './components/Cart';
import Customize from './components/Customize';
const App = () => {
return (
<>
<Router>
<Switch>
<Route exact path='/login'>
<Login />
</Route>
<Route exact path='/register'>
<Register />
</Route>
<div>
<Navbar />
<Route exact path='/'>
<Shop />
</Route>
<Route exact path='/order'>
<Order />
</Route>
<Route exact path='/item/details'>
<ItemDetails />
</Route>
<Route exact path='/cart'>
<Cart />
</Route>
<Route exact path='/customize'>
<Customize />
</Route>
<Route component={ErrorPage} />
</div>
</Switch>
</Router>
<Footer />
</>
);
}
export default App;
I searched about handling error page in react and I see that the order of routes is important but I don't get why I'm still getting the error page even it's in the bottom. Thank you guys.
That's because the switch component returns the first child at the root that meets the path condition. If the path condition doesn't exist it's evaluated as true. In your case you have 3 child Login, Register and the div which will always be evaluated to true. So just move all routes to the root of your switch:
<Router>
<Switch>
<Route exact path='/login'>
<Login />
</Route>
<Route exact path='/register'>
<Register />
</Route>
<div>
<Navbar />
<Switch>
<Route exact path='/'>
<Shop />
</Route>
<Route exact path='/order'>
<Order />
</Route>
<Route exact path='/item/details'>
<ItemDetails />
</Route>
<Route exact path='/cart'>
<Cart />
</Route>
<Route exact path='/customize'>
<Customize />
</Route>
<Route component={ErrorPage} />
</Switch>
</div>
</Switch>
</Router>

Can't show Error 404 Component in nested Component in React Router

I'm trying show Error component if matches not found, but nothing happens - when I choose non-existing route, I see only blank page.
The Main component adds sidebar menu in example and renders all it childes inside in rest.
When all Route componets placed directly inside Switch - all works (including Error).
But in example below, Error component does not render - if route does not match - only blank page.
If Error component placed inside Main, in that case it will be rendered even for existing routes.
import React from 'react';
import { Switch, Route } from "react-router-dom";
import Signin from "../../containers/Signin";
import Signup from "../../containers/Signup";
import Error from "../../containers/Error";
import Courses from "../../containers/Courses";
import Course from "../../containers/Course";
import Quiz from "../../containers/Quiz";
import Header from "../Header";
import "./App.css";
import Library from "../../containers/Library";
import QuizResults from "../../containers/QuizResults";
import Main from "../Main";
import StudentsList from "../../containers/StudentsList";
function App()
{
return (
<div className="App">
<Header isLogged={false}/>
<Switch>
<Route exact path='/' component={Signin} />
<Route path='/signup' component={Signup} />
<Main>
<Route path='/courses' component={Courses} />
<Route path='/course/:id' component={Course} exact/>
<Route path='/quiz' component={Quiz} />
<Route path='/library' component={Library} />
<Route path='/quiz-results' component={QuizResults} />
<Route path='/students' component={StudentsList} />
<Route component={Error} />
</Main>
</Switch>
</div>
);
}
export default App;
So, how to properly render Error component if no matches found?
Try using a wildcard.
<Route path="/*" component={Error} />
Add exact word to the route. And better approach will be to set the Error component name to NotFound or FourZeroFour . It will work then.
<Router>
<Switch>
<Route exact path='/' component={Signin} />
<Route exact path='/signup' component={Signup} />
<Main>
<Route exact path='/courses' component={Courses} />
<Route exact path='/course/:id' component={Course} />
<Route exact path='/quiz' component={Quiz} />
<Route exact path='/library' component={Library} />
<Route exact path='/quiz-results' component={QuizResults} />
<Route exact path='/students' component={StudentsList} />
<Route component={NotFound} />
</Main>
</Switch>
</Router>
Solution for this problem - place another Switch around Route components:
import React from 'react';
import { Switch, Route } from "react-router-dom";
import Signin from "../../containers/Signin";
import Signup from "../../containers/Signup";
import NotFound from "../../containers/NotFound";
import Courses from "../../containers/Courses";
import Course from "../../containers/Course";
import Quiz from "../../containers/Quiz";
import Header from "../Header";
import "./App.css";
import Library from "../../containers/Library";
import QuizResults from "../../containers/QuizResults";
import Main from "../Main";
import StudentsList from "../../containers/StudentsList";
function App()
{
return (
<div className="App">
<Header isLogged={false}/>
<Switch>
<Route exact path='/' component={Signin} />
<Route exact path='/signup' component={Signup} />
<Main>
<Switch>
<Route exact path='/courses' component={Courses} />
<Route exact path='/course/:id' component={Course} />
<Route exact path='/quiz' component={Quiz} />
<Route exact path='/library' component={Library} />
<Route exact path='/quiz-results' component={QuizResults} />
<Route exact path='/students' component={StudentsList} />
<Route path='*' component={NotFound} />
</Switch>
</Main>
</Switch>
</div>
);
}
export default App;

Categories

Resources