Science Knowings: JavaScript Course For Social Media

React Router

React Router

Recap: React Component Lifecycle

We've covered the React component lifecycle, including the different lifecycle methods and their usage.

Introducing React Router

Today, we embark on a journey to explore React Router, a powerful tool for creating single-page applications in React. React Router enables you to manage the navigation and routing of your application.

Why use React Router?

React Router offers several advantages:

  • Seamless Navigation: It provides a consistent and user-friendly navigation experience.
  • URL Management: React Router handles URL routing, allowing you to create dynamic and SEO-friendly URLs.
  • Code Splitting: Lazy loading with React Router helps improve performance by loading only the necessary components when needed.

Installing React Router

npm install react-router-dom

Creating a Simple Router

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

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element=<Home  />
        <Route path="/about" element=<About  />
      </Routes>
    </BrowserRouter>
  );
}

Using the Route Component

<Route path="/about" element=<About  />

The Route component defines a path and a React component to render when that path is matched.

Adding Navigation Links

<Link to="/about">About</Link>

Link component provides a way to navigate between routes.

Routing Parameters

<Route path="/user/:id" element=<User />

React Router supports dynamic routing using parameters. Here, :id is a wildcard that matches any user ID.

Lazy Loading

Lazy Loading with React.lazy and Suspense

const About = React.lazy(() => import('./About'));

<Suspense fallback=<Loading /> 
  <Route path="/about" element=<About />
</Suspense>

Authentication with React Router

React Router provides hooks like useNavigate and useLocation to manage authentication and authorization.

Redirect and Navigate

import { useNavigate } from 'react-router-dom';

const navigate = useNavigate();

navigate("/login"); // Redirects to the login page

Nested Routes

<Routes>
  <Route path="/" element=<Home />
  <Route path="/users" element=<Users >
 <Route path=":userId" element=<User />
  </Route>
</Routes>

Using Switch vs. Routes

Switch vs. Routes

Switch is deprecated in favor of Routes. Routes offers more flexibility and allows multiple routes to be rendered conditionally.

Handling Errors

Error Boundaries

React Router uses error boundaries to catch and display errors in your application.

Next Up: React Props

In our next session, we'll dive into React Props, essential for passing data between components. Follow us to learn more!