Reputation: 1127
I'm testing React Router in a project (It's one of my first times using it), and, for some reason the routes aren't working when i click the 'Links', but when I type the route directly in the url, and then refresh the page, it works, can someone help me with that?
Here's the code:
App Component
import React from "react";
import "./styles.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import NavBar from "./components/NavBar";
import ProductList from "./components/ProductList";
import Home from "./components/Home";
export default function App() {
return (
<div className="App">
<NavBar />
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/products" component={ProductList} />
</Switch>
</Router>
</div>
);
NavBar Component (For now, I haven't included the 'My Cart' in the Links)
import React from "react";
import { BrowserRouter as Router, Link } from "react-router-dom";
function NavBar() {
return (
<nav className="navbar navbar-light bg-dark p-3">
<Router>
<Link to="/">
<i className="fas fa-gifts fa-2x text-light ml-2" />
</Link>
<Link to="/products" className="btn text-light bg-dark mr-2 ml-auto">
Products
</Link>
</Router>
<button className="btn text-light bg-dark">
<i className="fas fa-shopping-cart" />
My Cart
</button>
</nav>
);
}
export default NavBar;
Upvotes: 0
Views: 43
Reputation: 291
This setup would work -
for App.js
import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import NavBar from "./components/NavBar";
import ProductList from "./components/ProductList";
import Home from "./components/Home";
export default function App() {
return (
<div >
<Router>
<Route path="/" component={NavBar} />
<Route path="/" exact component={Home} />
<Route path="/products" exact component={ProductList} />
</Router>
</div>
);
}
for NavBar.js
import React from "react";
import { BrowserRouter as Router, Link } from "react-router-dom";
function NavBar() {
return (
<nav className="navbar navbar-light bg-dark p-3">
<Link to="/">
<i className="fas fa-gifts fa-2x text-light ml-2" />
Home
</Link>
<Link to="/products" className="btn text-light bg-dark mr-2 ml-auto">
Products
</Link>
</nav>
);
}
export default NavBar;
Upvotes: 1