React Router: How to change path URL when redirect to a component by typing path?
Problem Description:
I just wanna stop the user to visit /profile
page until the user logs in, if the user tries to visit the profile page by typing /profile manually into the path then he/she will redirect to /login
page. So I’ve successfully redirected the user to the /login
page but the path didn’t change if they were redirected by typing /profile
into the path url.
How can I change the path once the redirection is complete?
Code:-
//App.js
const [profileUser, setProfileUser] = useState();
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
setProfileUser(user);
} else {
setUserName(null);
}
});
}, [profileUser]);
//JSX
return (
<div>
<Header loggedUser={profileUser} />
<MainWrapper>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<SignUp />} />
<Route
path="/profile"
element={
!profileUser ? <Login /> : <Profile loggedUser={profileUser} />
}
/>
</Routes>
</MainWrapper>
<Footer />
</div>
);
Solution – 1
You want to actually redirect to the "/login"
route instead of rendering the Login
component.
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<SignUp />} />
<Route
path="/profile"
element={profileUser
? <Profile loggedUser={profileUser} />
: <Navigate to="/login" replace /> // <-- Redirect
}
/>
</Routes>
Solution – 2
Simply try to add relace to="your path to need to redirect"
<Route path="/profile" element={profileUser ? <Profile loggedUser={profileUser} /> : <Navigate replace to="/login" />} />
import Navigate
from ‘react-router-dom’
Please check my answer here for another question regarding private routing.