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

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')
);

Related

Nothing shows up using react-router

I am new to React, and I cannot get my routes to work. I am following the tutorial in the documentation but somehow it does not work. The content inside the App component does not show up so I assume there is some kind of problem with BrowserRouter or Routes or my nesting but I really cannot figure out what's going on.
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import App from './App';
import Products from './routes/products';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
<Route path="products" element={<Products />} />
</Route>
</Routes>
</BrowserRouter>
</React.StrictMode>
);
routes/app.js
import { Outlet, Link } from "react-router-dom";
export default function App() {
return (
<div>
<h1>Hello World</h1>
<nav>
<Link to="/products">Products</Link>
</nav>
<Outlet />
</div>
);
}
routes/products.jsx
export default function Products(){
return (
<div>
<h1>Products</h1>
</div>
);
}
P.S. I already saw some stackoverflow answers but still I could not see what I am getting wrong.
EDIT:
Thank you for the attention and support but after rewriting the code and playing around with it I found out that my App component does not render when I add the Link to="" component. Any Idea why this is happening?
Try this router structure:
<BrowserRouter>
<Routes>
<Route index element={<App />}/>
<Route path="products" element={<Products/>}/>
</Routes>
</BrowserRouter>
I have made only one change to your code, i.e. I use a wildcard to redirect the user to App for each route that does not match the other routes (i.e. each route that does not match /products). You can add a wildcard with * like this: <Route path="*" element={<App />} />
index.tsx
import { StrictMode } from "react";
import * as ReactDOMClient from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { Products } from "./Products";
import App from "./App";
const rootElement = document.getElementById("root");
const root = ReactDOMClient.createRoot(rootElement);
root.render(
<StrictMode>
<BrowserRouter>
<Routes>
<Route path="*" element={<App />} />
<Route path="products" element={<Products />} />
</Routes>
</BrowserRouter>
</StrictMode>
);
App.tsx
import "./styles.css";
import { Link } from "react-router-dom";
export default function App() {
return (
<>
<Link to="/home">HOME</Link>
<Link to="/products">PRODUCTS</Link>
<div>HOME PAGE HERE</div>
</>
);
}
Products.tsx
import { Link } from "react-router-dom";
export const Products = () => {
return (
<>
<Link to="/home">HOME</Link>
<Link to="/products">PRODUCTS</Link>
<div>PRODUCTS PAGE HERE</div>
</>
);
};
You can checkout the example in codesandbox. Click on the links to navigate between the pages.
I am here answering my own question. After 2 days of madness I found out that I had two package.json files, so I just reinstalled locally react-router and eventually it worked. I came to this conclusion thanks to another answer here on StackOverflow.

React Project working but not displaying some components

i am trying to build a portfolio website using react and i am using react-router-dom for navigation.
everything was working for a while then i made a stupid mistake of keeping the project in onedrive and had some trouble.
link to code: https://github.com/Raghav-rv28/portfolio-website
Live: https://raghav-rv28.github.io/portfolio-website/, this is not really helpful as we cannot see anything but you can see the screenshots below,
when i run the project on my local machine it runs :
as you can see the elements are there but they just don't appear to me for some reason.
Some of the Code:
import React from 'react'
import {Route, Routes} from 'react-router-dom'
import Layout from './Components/Layout'
import Home from './Components/Home'
import About from './Components/About'
import Contact from './Components/Contact'
import Interests from './Components/Interests'
import Projects from './Components/Projects'
import './App.scss';
function App() {
return (
<>
<Routes>
<Route path="/" element = { <Layout />} >
<Route index element={< Home/>} />
<Route path='About' element={< About/>} />
<Route path='Contact' element={< Contact/>} />
<Route path='Interests' element={< Interests/>} />
<Route path='Projects' element={< Projects/>} />
</Route>
</Routes>
</>
);
}
export default App;
Layout.js:
import React from 'react';
import './index.scss';
import SideNavbar from '../SideNavbar/index';
import { Outlet } from 'react-router-dom';
export default function Layout(){
return(
<div className="App">
<SideNavbar />
<div className="page">
<Outlet />
</div>
</div>)
}
index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom'
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
You nested your routes for (Home, About, Contact, etc.) inside the "Layout" route. This means that react router will render BOTH "Layout" and whichever component is provided by a matching nested route.
Try restructuring your routes like this:
<>
<Routes>
<Route path="/" element = { <Layout />} />
<Route index element={< Home/>} />
<Route path='About' element={< About/>} />
<Route path='Contact' element={< Contact/>} />
<Route path='Interests' element={< Interests/>} />
<Route path='Projects' element={< Projects/>} />
</Routes>
</>
Turns out my stupid As* forgot to import the animation library i'm using and the opacity for the pages was set to 0.

ReactJS Route function isn't working for me

I started learning ReactJS yesterday using Academind's crash course for beginners on it. There is a part where he teaches about react-router-dom. I tried using it on App.js and index.js as such:
App.js:
import { Route } from "react-router-dom";
import AllMeetupsPage from "./pages/AllMeetups";
import FavouritesPage from "./pages/Favourites";
import NewMeetupsPage from "./pages/NewMeetups";
function App() {
return (
<div>
<Route path='/'>
<AllMeetupsPage />
</Route>
<Route path='/favourites'>
<FavouritesPage />
</Route>
<Route path='/new-meetups'>
<NewMeetupsPage />
</Route>
</div>
);
}
export default App;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom'
import './index.css';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
There shouldn't be any error since I have fixed the syntax and imported the right files given in the video. Yet, in localhost:3000 I get this as the result.
If I just use <AllMeetupsPage /> then it works. If I put it in the route function then it doesn't. How can I fix this?
When you are just using <AllMeetupsPage/> then it's directly rendering that page component in App.js.
It's actually not doing any routing.
To use multiple you also need to wrap it within .
<div>
<Routes>
<Route path="/" element={<AllMeetupsPage />} />
<Route path="/favourites" element={<FavouritesPage />} />
<Route path="/new-meetups" element={<NewMeetupsPage />} />
</Routes>
</div>
You can refer to the following link to get more context of the problem:
[1]: ReactJS: [Home] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
tyr this
import {Routes} from "react-router-dom"
<Routes>
<Route path='/'>
<AllMeetupsPage />
</Route>
<Route path='/favourites'>
<FavouritesPage />
</Route>
<Route path='/new-meetups'>
<NewMeetupsPage />
</Route>
</Routes>

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

React - How to include react router?

I'm new to react and I want to use the router to navigate bet pages/components. I couldn't find too much but was following one tutorial online but I don't think I'm doing it right as I'm only getting errors.
When I import router and then have this line: const { Router, Route ...} = ReactRouter; it gives me errors and I'm not sure how to do it right.
I'm not sure where to put the router path. I always see its being put into ReactDOM:render(...). I only render in my index.js file and it just seems wrong to me to put it there as I feel I should only render the App component (for good practice). Am I wrong?
Thanks a lot!
App.js:
import React from 'react';
import ReactDOM from 'react-dom';
import Router from'react-router'
const { Router, Route, IndexRoute, IndexLink, hashHistory, Link } = ReactRouter;
class App extends React.Component {
render () {
return (
<div>
<button><Link to="/page">Page</Link></button>
Router history={ReactRouter.hashHistory}>
<Route path="/" component={App}>
</Route>
<Route path="/page" component={Page}>
</Route>
</Router>
</div>
);
}
}
export default App;
index.js:
ReactDOM.render(<App/>, document.getElementById('app'));
There has been some changes after React router V4, and you should make sure that the code examples you find are right for the version you are using.
I am using v4, and this is what I do:
App.js:
import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
....
....
<BrowserRouter>
<Switch>
<Route path="/settings" component={Settings} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/login" component={Login} />
<Route path="/" component={Login} />
</Switch>
</BrowserRouter>

Categories

Resources