I just wanted to make a simple project setup with react-router-dom
but whenever I'm using route
the entire page becomes blank. my Nav disappears. why ?
there was a similar question for class component so it wasn't helpful for me.
App.js :
import "./App.css";
import Nav from "./components/Nav";
import Products from "./components/Products";
import About from "./components/About";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
function App() {
return (
<>
<Router>
<Nav />
<Route path="/about" component={About} />
<Route path="/products" component={Products} />
<About />
</Router>
</>
);
}
export default App;
Nav:
import React from "react";
import Navstyle from "../styles/Nav.module.css";
const Nav = () => {
return (
<nav className={Navstyle.Nav}>
<ul className={Navstyle.nav_links}>
<li>
<a href="!#">Home</a>
</li>
<li>
<a href="!#">Products</a>
</li>
<li>
<a href="!#">About</a>
</li>
</ul>
</nav>
);
};
export default Nav;
other components are just returning h2
tags
CodePudding user response:
You need to use a layout (as a HOC) to add a navbar or other things to your code. just use the components with routes in your router. I recommend defining the Layout in another file.
export default function App() {
return (
<Layout>
<Router>
<Route component={Products} path="/products" exact />
<Route component={About} path="/about" exact />
</Router>
</Layout>
);
}
const Products = () => {
return <p>Products</p>;
};
const About = () => {
return <p>about</p>;
};
const Navbar = () => {
return <p>navbar</p>;
};
const Layout = ({ children }) => {
return (
<div>
<Navbar />
<div>{children}</div>
</div>
);
};
CodePudding user response:
I find out ! the problem was YouTube videos I guess. first of all you must add BrowserRouter
to your index.js not app.js
, like this :
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById("root")
);
reportWebVitals();
after that you must use react router in that way , not the way I tried first :
import "./App.css";
import Nav from "./components/Nav";
import Products from "./components/Products";
import About from "./components/About";
import { Route, Routes } from "react-router-dom";
function App() {
return (
<>
<Nav />
<Routes>
<Route path="/About" element={<About />} />
</Routes>
</>
);
}
export default App;
during the changes of react-router-dom
in version 6 , this is the new way of using router.
the link of docs :
https://reactrouter.com/docs/en/v6/getting-started/overview