DEV Community

Taaha hussain Khan
Taaha hussain Khan

Posted on

Routing in React with React Router

Routing is an essential part of any single-page application (SPA), and React is no exception. In this post, we'll explore how to implement routing in a React app using the popular react-router library.

First, let's start by installing react-router-dom:


sh
npm install react-router-dom
Next, we’ll need to wrap our app in a BrowserRouter component and define our routes using the Route component:

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

const App = () => (
  <BrowserRouter>
    <Route path="/" exact component={Home} />
    <Route path="/about" component={About} />
    <Route path="/contact" component={Contact} />
  </BrowserRouter>
);
Each Route component defines a path and a component to render when the user navigates to that path. In the example above, when the user navigates to the root path (/), the Home component will be rendered. When the user navigates to /about, the About component will be rendered, and so on.

We can also use the Link component to create links between pages in our app:

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

const Navigation = () => (
  <nav>
    <ul>
      <li><Link to="/">Home</Link></li>
      <li><Link to="/about">About</Link></li>
      <li><Link to="/contact">Contact</Link></li>
    </ul>
  </nav>
);
By using react-router, we can easily implement routing in our React app. Happy coding!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)