Reputation: 47
I followed a tutorial on how to display multiple pages for my reactJS program and it partially works. I have two pages: Home and Stocks, and they both have some example text in them. When I type in /home, or /stocks at the end of my localhost URL, the pages change and the correct text displays. But after having 100% identical code to the tutorial, I don't get the links on my website.
//index.js
ReactDOM.render(
<Router>
<Routes>
<Route exact path="/home" element={<Home/>} />
<Route exact path="/stocks" element={<Stocks/>}/>
</Routes>
</Router>,
document.getElementById('root')
);
//app.js
function App() {
return (
<div className="App">
<NavBar />
<Route exact path="/home" component={Home} />
<Route exact path="/stocks" component={Stocks} />
</div>
);
}
//NavBar.js
function NavBar()
{
return (
<ul>
<li>
<Link to="/home">Home</Link>
</li>
<li>
<Link to="/stocks">Stocks</Link>
</li>
</ul>
);
}
There's no errors and everything works but only when I manually type in the pages. I am trying to have it so that when I type 'npm start', the home page automatically opens with links like: Home | Stocks, and then I can click whichever I want.
Upvotes: 0
Views: 219
Reputation: 1249
Change app.js and index.js alone like below,
app.js:
function App() {
return (
<div className="App">
<Router>
<NavBar />
<Routes>
<Route exact path="/home" element={<Home/>} />
<Route exact path="/stocks" element={<Stocks/>}/>
</Routes>
</Router>
</div>
);
}
index.js:
import { createRoot } from "react-dom/client";
import App from "./App";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<App />
);
Upvotes: 0
Reputation: 77
//index.js
ReactDOM.render(
<Router>
<Routes>
<Route path="/*" element={<App/>} />
</Routes>
</Router>,
document.getElementById('root')
);
//app.js
function App() {
return (
<div className="App">
<NavBar />
<Routes>
<Route index path="/home" component={<Home/>} />
<Route path="/stocks" component={<Stocks/>} />
</Routes>
</div>
);
}
Upvotes: 1
Reputation: 77
Which version of react router are you using? And also in your app.js file you need to fix the routes as i wrote down below.
//app.js
....
<Route exact path="/home" element={<Home />} />
<Route exact path="/stocks" element={<Stocks/>} />
...
Upvotes: 0