React Router Dom, render a component only for some routes [duplicate] - javascript

This question already has answers here:
How do I render components with different layouts/elements using react-router-dom v6
(2 answers)
Closed 8 months ago.
I have a React application with React Router Dom v6 and trying to render the Nav component when the path does NOT match the root "/" but I'm having trouble getting it to work. This is my code:
import { BrowserRouter as Router, Routes, Route, matchPath } from "react-router-dom";
import Nav from "./components/Nav/Nav";
import Home from "./components/Home/Home";
import Contributors from "./components/Contributors/Contributors";
const App = () => {
const match = matchPath({ path: "/", end: true }, "/");
return (
<Router>
{!match ? <Nav /> : null}
<Routes>
<Route path="/" exact element={<Home />} />
<Route path="/contributors" element={<Contributors />} />
</Routes>
</Router>
);
}
export default App;
How should I fix this?

Quick Solution:
You could simply do like below, adding the Nav where you want. I'm not sure if you can know the path in App, since it's not wrapped inside the Router.
import { BrowserRouter as Router, Routes, Route, matchPath } from "react-router-dom";
import Nav from "./components/Nav/Nav";
import Home from "./components/Home/Home";
import Contributors from "./components/Contributors/Contributors";
const App = () => {
return (
<Router>
<Routes>
<Route path="/" exact element={<Home />} />
<Route path="/contributors" element={<><Nav /><Contributors /></>} />
</Routes>
</Router>
);
}
export default App;
Improvement:
And if you want to take it further, instead of doing like above, you could set up a Layout component, like this:
import { Outlet } from "react-router-dom";
import Nav from "../Nav/Nav";
const Layout () => {
return (
<>
<Nav />
<Outlet />
</>
);
};
export default Layout;
And render the routes where you want the Nav trough the Layout:
import { BrowserRouter as Router, Routes, Route, matchPath } from "react-router-dom";
import Home from "./components/Home/Home";
import Contributors from "./components/Contributors/Contributors";
import Layout from "./components/Layout/Layout";
const App = () => {
return (
<Router>
<Routes>
<Route path="/" exact element={<Home />} />
<Route element={<Layout />}>
<Route path="/contributors" element={<Contributors />} />
</Route>
</Routes>
</Router>
);
}
export default App;

Related

Error "Error: A <Route> is only ever to be used as the child of <Routes> element"

I am trying to use routing for the first time and followed the exact instructions from Udemy:
File App.js:
import { Route } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (
<div>
<Route path = "/welcome">
<Welcome />
</Route>
<Route path = "/game">
<Game />
</Route>
<Route path = "/leaderboard">
<Leaderboard />
</Route>
</div>
);
}
export default App;
File index.js
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from "./App";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
I get the following error:
Error: A Route is only ever to be used as the child of
element, never rendered directly. Please wrap your Route in a Routes.
Where have I gone wrong?
Yes, in react-router-dom version 6 it is a bit different. Please look as the sample below.
React Router tutorial
import { render } from "react-dom";
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
import App from "./App";
import Expenses from "./routes/expenses";
import Invoices from "./routes/invoices";
const rootElement = document.getElementById("root");
render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="expenses" element={<Expenses />} />
<Route path="invoices" element={<Invoices />} />
</Routes>
</BrowserRouter>,
rootElement
);
There was a fairly decent change between versions 5 and 6 of react-router-dom. It appears that the Udemy course/tutorial is using version 5 where all you needed was a Router to provide a routing context and Route components just needed to be rendered within this context. In version 6, however, the Route components now need to be rendered within a Routes component (which is an upgrade from the v5 Switch component).
Introducing Routes
One of the most exciting changes in v6 is the powerful new <Routes>
element. This is a pretty significant upgrade from v5's <Switch>
element with some important new features including relative routing
and linking, automatic route ranking, and nested routes and layouts.
The error message is pretty clear, wrap your Route components in a Routes component. The routes also don't take children (other than other Route components in the case of nested routes), they render the components as JSX on the new element prop.
function App() {
return (
<div>
<Routes>
<Route path="/welcome" element={<Welcome />} />
<Route path="/game" element={<Game />} />
<Route path="/leaderboard" element={<Leaderboard />} />
</Routes>
</div>
);
}
The problem is your react-router-dom version.
Probably it's 5.1 or higher.
You can try (in terminal):
npm install react-router-dom#5.3.0
And then your code will be OK. Or you better rebuild your code according to new react-router-dom.
import React from 'react'
import {BrowserRouter, Route, Routes } from 'react-router-dom'
import './App.css';
import Navbar from './components/Navbar';
import { Home } from './components/screens/Home';
import { Login } from './components/screens/Login';
import { Profile } from './components/screens/Profile';
import { Signup } from './components/screens/Signup';
function App() {
return (
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<Signup />} />
<Route path="/profile" element={<Profile />} />\
</Routes>
</BrowserRouter>
);
}
export default App;
In the latest version of React, 'Switch' is replaced with 'Routes' and 'component' is replaced with 'element'
Enter image description here
Try to wrap your routes by Routes:
import { Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (
<div>
<Routes>
<Route path = "/welcome">
<Welcome />
</Route>
<Route path = "/game">
<Game />
</Route>
<Route path = "/leaderboard">
<Leaderboard />
</Route>
</Routes>
</div>
);
}
export default App;
I think there are many problems that can lead to that issue.
react-router-dom version 6 no longer supports the use of components directly. Use an element to specify the component you route.
Route has to be a child of Routes
Use the simple snippet.
import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar';
import {BrowserRouter, Routes, Route, Link} from 'react-router-dom';
import Homescreen from './screens/Homescreen';
function App() {
return (
<div className="App">
<Navbar/>
<BrowserRouter>
<Routes>
<Route path='/home' element={<Homescreen/>} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
The problem right here is that you are using React v5. Since React v6, several changes were included in Router.
So now, to make it work, and as your error message says, you need to wrap your Route element inside a Routes element (Routes now is the equivalent, but an improved version of Switch element). Also, you need to add an "element" prop that accepts JSX instead of wrapping inside the Route element.
So, to make it work, you need to import all these elements like this:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
That being said, your code should look like this:
<Router>
<Routes>
<Route path="/" element={<Welcome/>}>
</Route>
<Route path="/" element={<Game />}>
</Route>
<Route path="/" element={<Leaderboard />}>
</Route>
</Routes>
</Router>
It's probably because you are using version 6 or higher of react-router-dom.
Try:npm i react-router-dom#5.2.0
And it should work.
In the newer version of react-router-dom, we need to nest the Route inside the Routes. Also, component and exact have been removed in newer version.
I was facing same issue and solve it.
Though I am using
react-router-dom#6
So I had to modify app.js and index.js like below
in index.js
import { BrowserRouter } from "react-router-dom";
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
and app.js
import { Routes, Route } from "react-router-dom";
function App() {
return (
<>
<Header />
<main className="py-3">
<Container>
<Routes>
<Route path="/" element={<HomeScreen />} exact/>
</Routes>
</Container>
</main>
<Footer />
</>
);
}
export default App;
according to official documentation
Now, React uses React Router version 6
For React Router version 6, your index.js file is correct:
File index.js:
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from "./App";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
But your App.js file is not correct for React Router version 6, so this is the correct one below:
I changed three parts as shown below:
File App.js
// 1. "Routes" is imported
import { Routes, Route } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (
<div> // 2. With "<Routes></Routes>", surround "3 <Route /> tags"
<Routes> // 3. Put an element with a component to each "<Route />"
<Route path = "/welcome" element={<Welcome />} />
<Route path = "/game" element={<Game />} />
<Route path = "/leaderboard" element={<Leaderboard />} />
</Routes>
</div>
);
}
export default App;
Use the element option to set your component instead of nesting it into the route tags. Then wrap all the routes with <Routes></Routes>.
Do not forget to add Routes to your imports
import { Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (
<div>
<Routes>
<Route path = "/welcome" element={<Welcome />}/>
<Route path = "/game" element={<Game />}/>
<Route path = "/leaderboard" element={<Leaderboard />}/>
</Routes>
</div>
);
}
export default App;
Use:
<div>
<Header />
</div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
<Route path="/about" element={<About />} />
</Routes>
I know I'm late but there is another way to do nested routes straight from javascript.
first import
import { useRoutes } from "react-router-dom";
secondly, declare your routes. Here is a quick example
function App() {
return useRoutes([
{
path: "/",
element: <Example/>
},
{
path: "/contact",
element: <Example/>
}]);
}
so now you can have unlimited nested components doing it this way.
in your index.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root")); //where App must rendered in real DOM?in root
root.render(<App />); //jsx code is a special syntax that browser not undrestand it!
and in your App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import AllMeetupsPage from "./pages/AllMeetups";
import NewMeetupPage from "./pages/NewMeetup";
import FavoritesPage from "./pages/Favorites";
function App() {
return (
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<AllMeetupsPage />} />
<Route path="/new-meetup" element={<NewMeetupPage />} />
<Route path="/favorites" element={<FavoritesPage />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
There is another way to fix the version issues:
App.js File:
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (<div>
<BrowserRouter>
<Routes>
<Route path = "/Welcome" element={< Welcome/>}/>
<Route path = "/Game" element={< Game/>}/>
<Route path = "/LeaderBoard" element={< LeaderBoard/>}/>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
Index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

How to route to a path with parameters in React.js

I'm trying to make a news-feed website with React.js.
How to make a Router with the news ID?
I'm trying something like this:
<Route path="/news/:id">
{ ( {id} ) => <NewsPiece newsID={id}/> }
</Route>
But it didn't work out. I tried to look it up but didn't find any way convenience.
Below is my App.js being the main file.
import React from 'react';
import NavBar from './components/NavBar'
import Container from './components/Container'
import NewsPiece from './components/NewsPiece'
import Topics from './components/Topics'
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
function App() {
return (
<React.Fragment>
<NavBar/>
<Router>
<Switch>
<Route path="/news/:id">
{ ( {id} ) => <NewsPiece newsID={id}/> }
</Route>
<Route path="/news">
<Topics/>
</Route>
<Route path="/">
<Container/>
</Route>
</Switch>
</Router>
</React.Fragment>
);
}
export default App;
You should simply create a route like this -
App.js -
...
<Switch>
<Route path="/news/:id">
<NewsPiece />
</Route>
<Switch>
...
Now go to your component and access route parameter like this.
components/NewsPiece(assuming it's functional component) - ​
import { useParams } from 'react-router-dom';
function NewPiece = () => {
​....
​const { id } = useParams(); // you'll get the id present in URL route parameter
​....
}
export default NewPiece;
Explanation - react-router-dom provides a hook useParams which extracts all the route parameters present and gives us in an object with key-value pair.
Since you're already getting id from a route parameter you don't need to use extra props newsID for this.
Try this
import React from 'react';
import NavBar from './components/NavBar'
import Container from './components/Container'
import NewsPiece from './components/NewsPiece'
import Topics from './components/Topics'
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
function App() {
return (
<React.Fragment>
<NavBar/>
<Router>
<Switch>
<Route path="/news/:id">
<NewsPiece newsID={id}/>
</Route>
<Route path="/news">
<Topics/>
</Route>
<Route path="/">
<Container/>
</Route>
</Switch>
</Router>
</React.Fragment>
);
}
export default App;
If the error still happens comment the error msg
That's not the correct way to get the route params.
Your route should just be like this.
<Route path="/news/:id">
<NewsPiece/>
</Route>
You will get the value of your param inside the NewsPiece component using props.match.params.id
Here id is the param name you are using.
Try this then
import React from 'react';
import NavBar from './components/NavBar'
import Container from './components/Container'
import NewsPiece from './components/NewsPiece'
import Topics from './components/Topics'
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
function App() {
return (
<React.Fragment>
<NavBar/>
<Router>
<Switch>
<Route
path="/news/:id"
component = {NewsPiece newsID={id}}
</Route>
<Route path="/news">
<Topics/>
</Route>
<Route path="/">
<Container/>
</Route>
</Switch>
</Router>
</React.Fragment>
);
}
export default App;
If the error still continues . Its a problem with your importing method...

Trouble using nested routes in ReactJS

I want to use nested routes in my React app. I have the following MainSwitch:
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from '../Home/Home';
import Dashboard from '../Dashboard/Dashboard';
const MainSwitch = () => {
return (
<Switch>
<Route path='/' component={Home}></Route>
<Route path='/dashboard' component={Dashboard}></Route>
</Switch>
);
}
export default MainSwitch;
This wraps around the app:
import React from 'react';
import MainSwitch from './components/MainSwitch/MainSwitch';
import './css/Colors.css';
import './css/App.css';
function App() {
return (
<div>
<MainSwitch />
</div>
);
}
export default App;
Now in the Home component I have the following:
import React from 'react';
import HomeSwitch from '../HomeSwitch/HomeSwitch';
import NavbarDefault from '../NavbarDefault/NavbarDefault';
const Home = () => {
return (
<div>
<NavbarDefault />
<HomeSwitch />
</div>
);
}
export default Home;
The second switch HomeSwitch is as follows:
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Landing from '../Landing/Landing';
import Login from '../Login/Login';
import Signup from '../Signup/Signup';
import Pricing from '../Pricing/Pricing';
import NotFound from '../NotFound/NotFound';
const HomeSwitch = () => {
return (
<Switch>
<Route exact path='/' component={Landing}></Route>
<Route exact path='/login' component={Login}></Route>
<Route exat path='/signup' component={Signup}></Route>
<Route exact path='/pricing' component={Pricing}></Route>
<Route exact path="*"><NotFound /></Route>
</Switch>
);
}
export default HomeSwitch;
The reason I use two routers is because pages from Home and Dashboard will have different navigation bars etc.
If I navigate to any of the links in Home there are no issues. But if I try to navigate to /dashboard I get the NotFound page for the 404 error. What am I doing wrong here?
I guess you can just switch the order of the routes:
const MainSwitch = () => {
return (
<Switch>
<Route path='/dashboard' component={Dashboard}></Route>
<Route path='/' component={Home}></Route>
</Switch>
);
}
because this way when you try to go to /dashboard it'll first go through <Route path='/dashboard'. And since these are in a Switch, this path <Route path='/' only matches when the path doesn't start with /dashboard.
Replace <Route exat path='/signup' component={Signup}></Route> by <Route exact path='/signup' component={Signup}></Route>
Pay attention to the exact word instead of exat.
I had a routeing problem here because of the same mistake.

React Router Switch not rendering specific component

I have a React app that is currently using react-router#4.2.0 and I'm struggling with rendering a specific component when the URL changes.
When I try to visit /locations/new it returns with a PropTypes error from the CityList component. I have tried adding in exact to the Route component within LocationsWrapper and then Main config too, however, this then influences other routes - such as /locations to become null.
// BrowserRouter
import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import store from "./store";
import Navbar from "./components/Core/Navbar";
import Routes from "./config/routes";
render(
<Provider store={store}>
<BrowserRouter>
<div style={{ backgroundColor: "#FCFCFC" }}>
<Navbar />
<Routes />
</div>
</BrowserRouter>
</Provider>,
document.getElementById("root")
);
// Router config - ( Routes )
import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "../components/Home";
import Locations from "../components/Locations";
import CityList from "../components/CityList";
import CreateLocation from "../components/CreateLocation";
import Locale from "../components/Locale/index";
import Profile from "../components/Profile";
import NoMatch from "../components/Core/NoMatch";
import requireAuth from "../components/Core/HOC/Auth";
const LocationsWrapper = () => (
<div>
<Route exact path="/locations" component={Locations} />
<Route path="/locations/new" component={CreateLocation} />
<Route path="/locations/:id" component={CityList} />
</div>
);
const Main = () => (
<main>
<Switch>
<Route exact path="/" component={requireAuth(Home)} />
<Route path="/locations" component={LocationsWrapper} />
<Route path="/locale/:id" component={Locale} />
<Route path="/profile" component={requireAuth(Profile, true)} />
<Route component={NoMatch} />
</Switch>
</main>
);
export default Main;
Am I best avoiding <Switch> entirely and implementing a new method for routes that are undefined - such as 404s?
Yes, this will definitely return first
<Route path="/locations/:id" component={CityList} />
In react-router 4 there is no concept of index route, it will check each and every routes so in your defining routes are same
<Route path="/locations/new" component={CreateLocation} />
<Route path="/locations/:id" component={CityList} />
both path are same '/location/new' and '/location/:id' so /new and /:id are same params.
so at last 'CityList' will return
You can define like this
<Route path="/locations/create/new" component={CreateLocation} />
<Route path="/locations/list/:id" component={CityList} />
Pretty sure your route is not working cause you are also matching params with /locations/new with /locations/:id so then 'new' becomes Id param.
Try changing this
<Route path="/locations/new" component={CreateLocation} />
To something like this
<Route path="/locs/new" component={CreateLocation} />
Just a suggestion hope this may help

Declaring React Routes in a separate file and Importing

I am new to React. I have been trying to declare routes in a file and then use it in another file.
Here is my routes.js
import React from 'react';
import { Route } from 'react-router-dom';
import App from './components/App';
import Template1 from './components/template1';
import Template2 from './components/template2';
import Template3 from './components/template3';
const routes = (
<Route exact path="/" component={App}>
<Route exact path="/sessionstate1" component={Template1} />
<Route exact path="/sessionstate2" component={Template2} />
<Route exact path="/sessionstate3" component={Template3} />
</Route>
)
export default routes
and index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import './styles/css/index.css';
import routes from './routes.js';
ReactDOM.render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('root')
);
I am not getting any errors or warning but the page is not loading. Please tell me what I am missing
Thanks
well i had the same issue a few days ago, and the solution for me was this...
This one of the routes files:
import React from 'react';
import { Route } from 'react-router-dom';
import { ComponentY } from '../components/functionalitys';
export default [
<Route path="/appointment" component={ComponentY} exact key="create" />,
];
This another route file:
import React from 'react';
import { Route } from 'react-router-dom';
import { LoginPage, Register } from '../components/user';
export default [
<Route path="/register" component={Register} exact key="create" />,
<Route path="/login" component={LoginPage} exact strict key="login" />
];
And this is how I imported in the main app.js:
import routesFromFile1 from './the/route';
import routesFromFile2 from './the/other/route';
class App extends Component{
render(){
return(
<div className="wrapper">
<section className="content container-fluid">
<Switch>
<Route exact path="/" component={Home} strict={true} exact={true}/>
<Route path="/500" component={InternalServer} />
{routesFromFile1}
{routesFromFile2}
</Switch>
</section>
</div>
)
}
}
I hope this help Someone! Cheers!!
You don't need to wrap your Routes inside a div. Try something like this:
routes.js
import React from 'react';
import { Router, Route } from 'react-router';
import { Template1, Template2, Template3 } from './templates';
const createRoutes = () => (
<Router>
<Route exact path="/sessionstate1" component={Template1}/>
<Route exact path="/sessionstate2" component={Template2}/>
<Route exact path="/sessionstate3" component={Template3}/>
</Router>
);
export default createRoutes;
index.js
import ReactDOM from 'react-dom';
import createRoutes from './routes';
const routes = createRoutes();
ReactDOM.render(
routes,
document.getElementById('root')
);
index.js:
import LoginRoutes from './login/routes'
let routeConfig = [];
routeConfig = routeConfig.concat(LoginRoutes(store));
<Router routes={routeConfig}/>
routes.js:
export default (store) => {
return [
{path: '/login', component: Login},
{path: '/signup', component: SignUp},
]
}
This way you can add routes from different files and spread your route definitions to different folders that serve the contextual purpose of the route.
The store variable is there in case you want to use redux and want to have an onEnter event on the route. Example:
export default () => {
const sessionEnter = (location) => {
let {appId} = location.params;
store.dispatch(loadApp(appId));
return [
{path: '/apps/:appId', component: App, onEnter: sessionEnter},
]
}
I find onEnter events a good alternative to componentDidMount, data-fetching-wise. Invoking a data fetch on route level makes more sense to me as I see the component as part of the presentation level.
I think the problem is with wrapping the Route inside a div.
Try wrapping them inside a Route like following. Try this fiddle and change the routes wrapper to div.
const routes=(
<Route >
<Route exact path="/sessionstate1" component={Template1}/>
<Route exact path="/sessionstate2" component={Template2}/>
<Route exact path="/sessionstate3" component={Template3}/>
</Route >
)
export default routes;
And import it into index.js
import routes from './routes.js';
ReactDOM.render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('root')
);
With Typescript
Sepate the file for routes as routes.ts
export const routes = [
{ path: '/', component: Home },
{ path: '/auth-callback', component: authCallback },
{ path: '/fetch-data/:startDateIndex?', component: FetchData }
];
In the App.tsx
export function App() {
const routeComponents = routes.map(({ path, component }, key) => <Route exact path={path} component={component} key={key} />);
return (
<Layout>
{routeComponents}
</Layout>
);
}
Layout.tsx
export default (props: { children?: React.ReactNode }) => (
<React.Fragment>
<div>
<NavMenu />
<TopAppBarFixedAdjust>
{props.children}
</TopAppBarFixedAdjust>
</div>
</React.Fragment>
);
I know I'm little late but here my working
here a working demo
my dependencies are
"react": "16.2.0",
"react-dom": "16.2.0",
"react-router-dom": "4.2.2",
"react-scripts": "1.1.0"
create nav.js file as this
this file is responsible for storing all the links for navbar
import React, { Component } from "react";
import { Link } from "react-router-dom";
class Navi extends Component {
render = () => (
<div>
<Link to="/">Go to Home</Link> <br />
<Link to="/about">Go to About</Link> <br />
<Link to="/any-route">404 page</Link>
</div>
);
}
export default Navi;
Then the routes.js file
here you will define all your routes, and your pages where the routes should navigates to
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
// your components
const Home = () => <h1>Home</h1>;
const About = () => <h1>About</h1>;
const MissingPage = () => <h1>404</h1>;
const routes = (
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route component={MissingPage} />
</Switch>
);
export default routes;
finally here is the code for index.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import Navi from "./nav";
import routes from "./routes";
// initialize rotues and navi links
const initRoutes = () => (
<Router>
<div>
<Navi />
{routes}
</div>
</Router>
);
const initializedRoutes = initRoutes();
ReactDOM.render(
initializedRoutes,
document.getElementById("root")
);
This is the routing page created
routing page imported
Hope, it will help everyone. click the link to see code.!!
In react-router-dom version 6.x.x
Suppose you have the following URLs in your react app
/
/home
/handlers
/handlers/notes
/handlers/users
you can isolate all routing components related to handlers(including its nested URLs) by:
Define your main routing
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/home" element={<HomePage />} />
<Route path="/handlers/*" element={<AllHandlersPages />} />
</Routes>
</BrowserRouter>
Notice the existence of path="/handlers/*" where we have a wildcard * to tell react-router-dom to match with any nested route too
then
declare AllHandlersPages in another file like this
export function AllHandlersPages() {
return (
<Routes>
<Route>
<Route index element={<HandlersIndexPage />} />
<Route path="notes" element={<NotesPage />} />
<Route path="users" element={<UsersPage />} />
</Route>
</Routes>
);
}
Because <Route /> can't be defined unless it has a parent <Routes /> don't forget to make them nested properly.
Full working Demo
Try it like this way
import React from "react";
import {HashRouter as Router, Route} from 'react-router-dom';
import NoteContainer from "./component/note/index.jsx";
import Header from "./component/common/header.jsx";
const App = (props) => {
return (
<div className="container">
<Header/> {props.children}
</div>
);
};
var x = () => {
return (
<h1>Hello world!</h1>
);
};
module.exports = () => {
return (
<Router>
<App>
<Route path="/" component={NoteContainer}/>
<Route path="/inbox" component={x}/>
</App>
</Router>
);
};
I did it with very simple way. Follow the two steps below.
In App.js
import "bootstrap/dist/css/bootstrap.min.css";
import Header from "./component/common/header";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import routes from "./routes";
function App() {
return (
<Router>
<section className="container">
<Header />
{routes}
</section>
</Router>
);
}
export default App;
in routes.js
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import Overview from "./component/overview/overview";
import UsersList from "./component/userslist/UsersList";
import FavUserList from "./component/userslist/FavUserList";
const routes = (
<Switch>
<Route exact path="/" component={Overview} />
<Route path="/adduser" component={UsersList} />
<Route path="/favuser" component={FavUserList} />
</Switch>
);
export default routes;
Note: Make sure you import like this
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
In < Header /> component you have to declare navigation link.
i'm starting into react too, and i figured out a way to make what you are looking for.
What i did was inside the app file (which comes default in every project) i imported the routes file, the routes file is located in a folder called approuter (you can name it whatever you want), i'll write some of my code so you can see what i mean
//APP FILE
import AppRouter from './router/approuter'
function App() {
return (
<>
<div className='app' id="mode">
<AppRouter />
</div>
</>
)
}
export default App
//ROUTER FILE/
import { Route, Routes } from 'react-router-dom'}
import Register from "../pages/register"
import Login from "../pages/login"
export default function AppRouter() {
return (
<>
<div>
<Routes>
<Route path="login" element={<Login />}/>
<Route path="register" element={<Register />}/>
</Routes>
</div>
</>
)
}
This actually worked in a project i'm currently working on, i hope this can answer your question
**index.js**
import ReactDOM from "react-dom/client";
import Paths from "./routes/Paths";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Paths />
</React.StrictMode>
);
**Paths.js**
import LoginSample from "../portal/LoginSample";
import Dashboard from "../portal/Dashboard";
function Paths() {
return (
<Router>
<Routes>
<Route path="/" element={<LoginSample />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Router>
);
}
export default Paths;
Also new to react and was running into the same issue. Here is what I tried (obviously different code and structure, but what we're looking for should be the same functionality)
index.js
import React from "react";
import ReactDOM from "react-dom";
import { createHashHistory } from "history";
import { BrowserRouter, Route } from 'react-router-dom';
import routes from "./routes";
const allRoutes = routes;
ReactDOM.render(
allRoutes,
document.getElementById("app")
)
and the routes.js file.
import React from "react";
import { createHashHistory } from "history";
import { BrowserRouter, Route } from 'react-router-dom';
import App from "./pages/App";
import Detail from "./pages/Detail";
import List from "./pages/List";
const routes = (
<BrowserRouter>
<div>
<Route exact path="/" component={ App } />
<Route path="/" component={ List } />
<Route path="/detail/:repo" component={ Detail } />
</div>
</BrowserRouter>
);
export default routes;
Let me know if that works for you.

Categories

Resources