Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Last active February 9, 2024 06:26
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save luisjunco/cbd1fe157c7f2f2b6b4983adbea9ae1e to your computer and use it in GitHub Desktop.
Save luisjunco/cbd1fe157c7f2f2b6b4983adbea9ae1e to your computer and use it in GitHub Desktop.
React Router Cheatsheet

React Router Cheatsheet

  • This cheatsheet is based on React Router Dom v6.7.0
  • If you use a different version, some things may be different




Initial Setup

  • Install:

    npm install react-router-dom
    
  • Configure <BrowserRouter>:

    • This is a root component so that you can use other functionality from React Router.

    • Usually you want to add <BrowserRouter> around your App component.

    • For example, if you're using "Vite", you can add it in main.jsx:

      //...
      import { BrowserRouter } from 'react-router-dom';
      //...
      
      ReactDOM.createRoot(document.getElementById('root')).render(
        <React.StrictMode>
          <BrowserRouter>
            <App />
          </BrowserRouter>
        </React.StrictMode>,
      )
      • Note: in some places (documentation, labs, etc), you may see that imported with an alias. For example:

      //...
      
      import { BrowserRouter as Router } from 'react-router-dom';
      
      //...
      
      <Router>
        <App />
      </Router>




Basic Routing

Example:

  • You can find an example here

Steps:

  • Create your routes using the components Routes and Route:

    //...
    import { Routes, Route } from "react-router-dom";
    //...
    
    function App() {
      return (
        <div className="App">
    
          {/* ...  */}
    
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
            <Route path="*" element={<ErrorPage />} />
          </Routes>
    
          {/* ...  */}
    
        </div>
      );
    }
    
    export default App;
  • Add a navigation menu, so that users can go to those routes.
    Do not use <a> tags (they will lead to a page reload).
    Instead, we can use the components <Link> or <NavLink>:

    //...
    import { Routes, Route, Link, NavLink } from "react-router-dom";
    //...
    
    export default function App() {
      return (
        <div className="App">
        
          <nav>
            <Link to="/">Home</Link>
            <Link to="/about">About</Link>
            <Link to="/contact">Contact</Link>
          </nav>
    
    
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
            <Route path="*" element={<ErrorPage />} />
          </Routes>
          
          {/* ...  */}
                 
        </div>
      );
    }

Notes:

  • In the prop element, you can pass any valid JSX. For example:

      <Route path="/contact" element={<div><h1>title</h1><h2>Subtitle</h2></div>} />
  • You can also pass properties. Ex:

    <Route path="/menu" element={<Menu pizzas={pizzasArr} msg="i love pizza" />} />
  • Anything that you put outside the component <Routes>, will be rendered for all pages (for example, if you want to display the header or a footer in all pages).




Basic Routing with NavLink

Example:

  • You can find an example here

How:

  • Instead of <Link>, you can also use <NavLink> (it adds the class "active" to the html link when the user is navigating on a specific page).

    <nav>
      <NavLink to="/">Home</NavLink>
      <NavLink to="/about">About</NavLink>
      <NavLink to="/contact">Contact</NavLink>
    </nav>
  • You will also need to add some CSS. For example:

    .nav a {
      color: blue;
    }
    .nav a.active {
      color: orange;
    }




URL Parameters

Example:

  • You can find an example here

Steps:

  • Define a dynamic route, using the following syntax:

      <Routes>
        ...
        <Route path="/users/:userId" element={<UserDetails />} />
        ...
      </Routes>
  • From the component, you can access the dynamic part of the URL using the hook useParams.

    The useParams hook returns an object of key/value pairs of the dynamic params from the current URL that were matched by the

    //...
    import { useParams } from "react-router-dom";
    //...
    
    function UserDetails() {
    
      const { userId } = useParams(); //useParams returns an object
      
      console.log(userId);
      console.log(typeof userId); //String (url params are always strings)
    
      //...
      //...
      
    }
  • Finally, don't forget to provide a way for the user to reach those dynamic routes.
    For example, a component to display a list of available resources:

    function UsersList() {
      return (
        <>
          <h3>List of users in our DataBase:</h3>
    
          {usersArr.map((user) => {
            return (
              <div className="card user">
                <h3>{user.name}</h3>
                <p>Id: {user.id}</p>
    
                <Link to={`/users/${user.id}`}>More details</Link>
              </div>
            );
          })}
        </>
      );
    }




Query Strings

Example:

  • You can find an example here

Steps:

  • Create the route with the following syntax:

    <Route path="/pizzas" element={<PizzasList />} />
  • In the component corresponding to that route, can use useSearchParams to read the query string. For example:

    //...
    import { useSearchParams } from "react-router-dom";
    //...
    
    function PizzasList() {
      const [searchParams, setSearchParams] = useSearchParams();
    
      const maxPrice = searchParams.get("maxPrice");
    
      console.log(maxPrice);
      console.log(typeof maxPrice); //String (search params are always strings)
    
      //... 
      //... 
      //...
    
    }
  • Finally, remember to provide a way for the user to reach that functionality. For example:

    <Link to="/pizzas?maxPrice=12">Find pizzas with max price 12</Link>
    <Link to="/pizzas?maxPrice=15">Find pizzas with max price 15</Link>




Redirect in your JSX (with <Navigate>)

A <Navigate> element changes the current location when it is rendered.

Example:

 
function MyComponent(props) {
  
  //...
 
  if (!props.isLoggedIn) return <Navigate to="/error" />;
 
  return (
    <div>
      <h1>Main Title</h1>
      {/*  */}
    </div>
  );
}




Redirect programmatically (with the hook useNavigate):

To redirect the user programmatically (for example, when the user submits a form, once you get the response from the API), you can use the custom hook useNavigate.

The useNavigate hook returns a function that lets you navigate programmatically.

For example:

//...
import { useNavigate } from "react-router-dom";
//...

function PizzaDetails(){

    const navigate = useNavigate();


    const deletePizza = () => {
        axios.delete(API_URL + "/pizzas/" + pizzaId)
            .then( response => {
                console.log("your pizza was deleted....");

                navigate("/"); //send the user to the homepage
            })
            .catch((e) => {
                console.log("oops...", e);
            });
    }


    //...

}
@luisjunco
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment