[Solved] Error: A <Route> is only ever to be used as the child of <Routes> element
React JS
Safiul Tarek
Problem:
I am trying to use routing But getting 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 Route
So here I am analyzing all the possible solutions here.
Solution 1:
Just Use route in this way
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
);
Solution 2:
Another way to use route. Just wrap your routes by Routes
import { Route, Routes } from "react-router-dom";
import Welcome from "./Pages/child1";
import Game from "./Pages/child2";
function App() {
return (
<div>
<Routes>
<Route path = "/child1">
<Welcome />
</Route>
<Route path = "/child2">
<Game />
</Route>
</Routes>
</div>
);
}
export default App;
Solution 3:
Here we solved this one change that is the multiple routes are now enclosed within a <Switch> tag
import React from "react";
import "./App.css";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from "react-router-dom";
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route path="/child1">
<div>
<p>This is child route 1</p>
</div>
</Route>
<Route path="/child2">
<div>
<p>This is child route 2</p>
</div>
</Route>
</Switch>
</Router>
</div>
);
}
export default App;
Thank you for reading the article. If you face any problem then comment below.