Home > other >  About react error in Route v6 (privateroute)
About react error in Route v6 (privateroute)

Time:03-29

I write this code for creating login form in React App. It is used Route library version 6. But it`s not working in return <Navigate to = "/login/">. I want to redirect people who are not logged in.

PrivateRoute.js

import {  useNavigate} from 'react-router-dom';
import { useAuthContext } from '../AuthContext';



const PrivateRoute = ({ children }) => {
  const { user } = useAuthContext();
  const Navigate = useNavigate();
  console.log(user);
  if (user) {
    return children;
  } else {
    return <Navigate to="/login"/>; //→Error
  }
};

export default PrivateRoute;

App.js

import Home from './components/Home';
import SignUp from './components/SignUp';
import Login from './components/Login';

import { AuthProvider } from './AuthContext';

import {BrowserRouter,Route,Routes,useNavigate} from 'react-router-dom';
import PrivateRoute from './components/PrivateRoute';



function App() {
  return (
    <AuthProvider>
      <div style={{ margin: '2em' }}>
        <BrowserRouter>
        <Routes>
          <Route path="/" element={<PrivateRoute><Home/></PrivateRoute>}></Route>
          <Route path="/signup" element={<SignUp/>}></Route>
          <Route path="/login" element={<Login/>}></Route>
        </Routes>
        </BrowserRouter>
      </div>
    </AuthProvider>
  );
}

export default App;

Error message

react-dom.development.js:14169 Uncaught Error: Component(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

CodePudding user response:

useNavigate returns a function and not a component.

You probably want something like

const PrivateRoute = ({ children }) => {
  const { user } = useAuthContext();
  const navigate = useNavigate();

  if (!user) {
    navigate("/login");
    return <></>;
  }

  return children;
};

CodePudding user response:

react-router-dom ships with the two components { Navigate, useNavigate }. if you want to use the Navigate component, you can just import it and then use it.

import { Navigate } from 'react-router-dom' // import it directly
    
const PrivateRoute = ({ children }) => {
  const { user } = useAuthContext();

  if (user) {
    return children;
  } else {
    return <Navigate to="/login" />
  }
};
  • Related