DEV Community

khaled-17
khaled-17

Posted on

The React Router Cheatsheet

Basic Router Setup:-

import { BrowserRouter as Router } from 'react-router-dom';
export default function App() {
return (
<Router>
{/* routes go here, as children */}
</Router>
);
}

Enter fullscreen mode Exit fullscreen mode

Route Component

Basic declaration

import { BrowserRouter as Router, Route } from 'react-router-dom';
export default function App() {
return (
<Router>
<Route path="/about" component={About} />
</Router>
);
}
function About() {
return <>about</>
}
Enter fullscreen mode Exit fullscreen mode

Basic declaration & 404 Route

import React from "react";
import ReactDOM from "react-dom/client";

import {
  createBrowserRouter,
  createRoutesFromElements,
  Route,
  RouterProvider,
} from "react-router-dom";

import NotFoundpage from "./NotFoundpage.jsx";
import SignIn from "./SignIn.jsx";
import SignUp from "./SignUp.jsx";
import ForgotPassword from "./ForgotPassword.jsx";

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route>
      <Route path="SignIn" element={<SignIn />} />
      <Route path="SignUp" element={<SignUp />} />
      <Route path="ForgotPassword" element={<ForgotPassword />} />
      <Route path="*" element={<NotFoundpage />} />
    </Route>
  )
);

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

Enter fullscreen mode Exit fullscreen mode

ProtectedProvider

import { Navigate } from "react-router-dom";
const ProtectedProvider = ({  children }) => {
     const logining = localStorage.getItem('authData'); 
     if (!logining) {
        return <Navigate to="/SignIn" replace />;
    } else {
             return children;         
    }
};
export default ProtectedProvider;



Enter fullscreen mode Exit fullscreen mode
  • and we use it like
 <Route>
      <Route path="SignIn" element={<SignIn />} />
      <Route path="SignUp" element={<SignUp />} />
           <Route path="myprofile" element={<ProtectedProvider><myprofile/></ProtectedProvider>} />

      <Route path="*" element={<NotFoundpage />} />
    </Route>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)