I’m trying to create a simple application focused on React router
.
I would like that after clicking on the Login button(there will be a form
for authentication in the component), the user will be redirected to the Menu page(Navigation component).
In this case, it looks like I click the button, but only the URL
changes.
I tried to add Routes
and Route
component to Login component…)
<div>
<Link to="/home" >
Login
</Link>
<Routes>
<Route path="/home" element={<Home />} />
</Routes>
</div>
but in this case the Menu works in such a way that when I click on the Link
e.g. about, the About component is not displayed.
So I don’t know if there is a bug somewhere between the Navigation
and Login components or if I’m going about it completely wrong.
index.js
import "bootstrap/dist/css/bootstrap.css";
import React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
const baseUrl = document.getElementsByTagName("base")[0].getAttribute("href");
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<BrowserRouter basename={baseUrl}>
<App />
</BrowserRouter>
);
App.js
import React from "react";
import Login from "./components/Login";
const App = () => {
return (
<div>
<Login />
</div>
);
};
export default App;
Login.jsx
import React from "react";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import Home from "./Home";
const Login = () => {
return (
<div>
<Link to="/home" style={{ padding: 5 }}>
Login
</Link>
</div>
);
};
export default Login;
3
Answers
Hey Peter I had the same issues a while ago. While I can’t point to you exactly whatsup without reading your code, Here is what saved me a lot.
Have a quick read here.
https://blog.logrocket.com/react-router-v6-guide/
Cheers!
Also, check if you wrapped your component routes like this;
In the sandbox only the
Login
component is rendered by theApp
component.If you want
Login
to be rendered on the root"/"
route, alone without the nav menu, then these are the changes I suggest:Refactor
MyOutlet
to render theNavigation
component andRoutes
and various routes. Add a route on"/"
for theLogin
component. Create a new layout route component to render theNavigation
component with anOutlet
for nested routes and wrap all but the"/"
route.Remove
Navigation
from theHome
componentUpdate
App
to render the updatedMyOutlet
component.Update the
Navigation
component to render just the links.Demo
router you need to put your routes file in your app.js so that your browser can render your routes first and this way you can have a signle page application (SPA) and always have a route with path="/" it’s the first page that when someone visites your page see
i changed your app.js and MyOutlet hope this helps
code that i edited in sandbox