DEV Community

Visakh Vijayan
Visakh Vijayan

Posted on • Originally published at dumpd.in

Mastering Navigation with React Router: A Comprehensive Guide

React Router is a vital tool for managing navigation in React applications. Let's delve into the key aspects of React Router:

Setting Up Routes

To get started with React Router, install it using npm:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Define routes in your main component:

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

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path='/' component={Home} />
        <Route path='/about' component={About} />
      </Switch>
    </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

Dynamic Routing

Handle dynamic routes using parameters:

<Route path='/user/:id' component={User} />

function User(props) {
  const { id } = props.match.params;
  return <div>User ID: {id}</div>;
}
Enter fullscreen mode Exit fullscreen mode

Programmatic Navigation

Redirect users programmatically:

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

function Home() {
  const history = useHistory();

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

  return (
    <button onClick={handleClick}>Go to About</button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Optimizing User Experience

Implement nested routes for complex UI structures:

<Route path='/products' component={Products} />

function Products() {
  return (
    <div>
      <h3>Products</h3>
      <Route path='/products/:id' component={ProductDetails} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Mastering React Router empowers you to create dynamic and user-friendly navigation experiences in your React applications.

Top comments (0)