'react route component is not rendering anything
I created my app with create-react-app and tried to use react-router on it. but it's not working at all. I am using react-router-dom 5.3.0 version. But if I type page path in URL and then reload the site, components will render. Please help me out.
Here is my app.js
import "./App.css";
import NavBar from "./Components/NavBar";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import LogIn from "./Components/LogIn";
import Home from "./Components/Home";
function App() {
return (
<>
<Router>
<NavBar />
<Switch>
<Route path="/" component={Home} exact/>
<Route path="/login" component={LogIn}/>
</Switch>
</Router>
</>
);
}
export default App;
Here is my NavBar
import React from 'react';
import '../App.css';
import {Link } from 'react-router-dom';
export default function NavBar() {
return (
<div className='Navbar'>
<h3 className='title'>Mero Blog</h3>
<ul>
<li>
<Link to='/'>Home</Link>
</li>
<li>
<Link to='/'>💡</Link>
</li>
<li className='drop'>
Profile
<ul className='option'>
<li>
<Link to='/'>See Profile</Link>
</li>
<li>
<Link to='/'>Log Out</Link>
</li>
</ul>
</li>
<li>
<Link to='/login'>Log In</Link>
</li>
</ul>
</div>
)
}
Here is my index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
Solution 1:[1]
I think the problem with React18. If you change index.js to
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
then it will work but ReactDOM.render is no longer supported in React 18. If you have resolved this issue, please let me know. One more thing => React 18: react-router@v5 is breaking in the Strict Mode, so without Strict Mode Its work for me
root.render(
<BrowserRouter>
<React.StrictMode>
<App/>
</React.StrictMode>
</BrowserRouter>
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |