React Router: Navigation in React Applications


  In React, React Router is the most popular library for managing navigation between different views or pages within an application. It allows you to create dynamic routes and navigate between them without reloading the page. Let's learn how to set it up and use it in your React applications.


What is React Router?

  React Router is a library for handling routes in React applications. It allows you to create a declarative navigation architecture, meaning routes are explicitly defined within your code, and React Router takes care of rendering the appropriate component based on the URL.


  • Links: React Router uses the Link component to navigate between different routes without reloading the page.
  • Routes: The Route component is used to define which component should be rendered for a specific URL.
  • Switch: The Switch component is used to ensure that only one route is rendered at a time.

  Let's look at a basic example of how to configure React Router:

import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';

const App = () => {
  return (
    <Router>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </Router>
  );
};

const Home = () => <h2>Welcome to the Home page</h2>;
const About = () => <h2>This is the About page</h2>;

Programmatic Navigation

  React Router also allows for programmatic navigation, meaning we can change the route using JavaScript code instead of just through links. This is achieved by using the useHistory hook.


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

const NavigateButton = () => {
  const history = useHistory();

  const handleClick = () => {
    history.push('/about');
  };

  return <button onClick={handleClick}>Go to About</button>;
};

Nested Routes

  In more complex applications, it's common to have nested routes, where one route is located within another. React Router allows you to define routes within other routes using the Route component inside another Route component.


const App = () => {
  return (
    <Router>
      <Route path="/" component={Layout}>
        <Route path="profile" component={Profile} />
        <Route path="settings" component={Settings} />
      </Route>
    </Router>
  );
};


How can you programmatically navigate in React Router? What is navigating in React Router? What is a browser-router in React? How does React Router work? What is navigation in React? What is navigation in React Router? React router-dom React Router v6 React Router-dom documentation React Router-example React-router - npm React Router 7 React Router alternatives Npm react-router-dom