Search code examples
javascriptreactjsreact-router-dom

React Router 6 doesn't redirect to page


I wrote a private router. It works correctly with props but doesn't redirect when props are wrong. Could you help me with this issue? Here is a snippet of my code:

export function PrivateRoute({ children, ...rest }) {
const navigate = useNavigate();
const { props } = rest;
return (
    <Routes>
        <Route
            {...rest}
            render={() => (props === 'admin' ? children : navigate(url))}
        />
    </Routes>
);
}

Solution

  • You should be using the Navigate component since you are in JSX, the useNavigate hook is for when you are outside, like so:

    import {Navigate} from "react-router-dom" // what to use inside JSX
    export function PrivateRoute({ children, ...rest }) {
    const { props } = rest;
    
    const navigate = useNavigate(); // that is for when you are outside of JSX
    navigate("/someRoute"); // how you would redirect when you are outside of JSX
    
    //Inside JSX, you would use the Navigate component like below.
    return (
        <Routes>
            <Route
                {...rest}
                render={() => (props === 'admin' ? children : <Navigate to ={url}/>)}
            />
        </Routes>
    );
    }