I have this error message
Error: A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .
with this code
import './App.css';
import Header from './Components/Header';
import React, {Component} from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Home from "./Components/Home";
import Services from "./Components/Services";
import Contact from "./Components/Contact";
function App() {
return (
<Router>
<div>
<Link to="/">Home</Link>
</div>
<div>
<Link to="/services">Blog Articles</Link>
</div>
<div>
<Link to="/contact">Contact Me</Link>
</div>
<hr />
<Route exact path="/">
<Home />
</Route>
<Route path="/services">
<Services />
</Route>
<Route path="/contact">
<Contact />
</Route>
</Router>
);
}
export default App;
Please how do i resolve this
CodePudding user response:
You need to wrap your <Route />
components with <Switch />
component(as per documentation):
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/services">
<Services />
</Route>
<Route path="/contact">
<Contact />
</Route>
</Switch>
CodePudding user response:
Solution: 01
You can try using routes instead of Switch.
import { BrowserRouter, Routes, Route} from "react-router-dom";
<BrowserRouter>
<Routes>
<Route exact path="/" element={<Home />}>
<Home/>
</Route>
</Routes>
</BrowserRouter>
Solution: 02
Did you try wrapping your Route tags in a switch? For example,
<Router>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/register" component={SignUp}/>
<Route exact path="/login" component={Login}/>
<Route exact path="*" component={Error}/>
</Switch>
</Router>
Solution: 03
Switch is replaced in react-router-dom version 6. So that you need to install react-router-dom version 5. Now, your error should be solved.
npm install react-router-dom@5
CodePudding user response:
try this for routing:
import { BrowserRouter, Switch, Route, Redirect } from "react-router-dom";
function App() {
return (
<div className="app">
<BrowserRouter>
<Navbar />
<Switch>
<Route path="/post/create" exact>
<Form />
</Route>
<Route path="/:username" exact>
<Profile />
</Route>
<Route path="/accounts/edit" exact>
{user ? <EditProfile /> : <Redirect to="/login" />}
</Route>
<Route path="/direct/:id" exact>
{user ? <Direct /> : <Login />}
</Route>
<NotFound404 />
</Switch>
</BrowserRouter>
</div>
);
}
export default App;