Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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>
);

}

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>
);
}
about 4 years ago · Juan Pablo Isaza Report

0

import React, { useContext, useEffect } from 'react';

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
} from 'react-router-dom';

import { AuthContext } from '../context/AuthContext';
import ChatPage from '../pages/ChatPage';
import LoginPage from '../pages/LoginPage';

import AuthRouter from './AuthRouter';

const AppRoutes = () => {
  const { auth } = useContext(AuthContext);

  return (
    <Router>
      <div>
        <Routes>
          <Route path="auth/*" element={!auth.logged ? <AuthRouter /> : <Navigate to="/" />} />
          <Route path="/" element={auth.logged ? <ChatPage /> : <Navigate to="auth/login" />} />
          <Route path="*" element={<LoginPage />} />
        </Routes>
      </div>
    </Router>

  );
};

export default AppRoutes;

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!