Codementor Events

Simplest way to add routing in React

Published Mar 30, 2023Last updated Jan 10, 2024
Simplest way to add routing in React

In React, you can implement routing using the React Router library. React Router is a popular and the simpler library for managing routing in single-page applications built with React.

Here are the basic steps for implementing routing in a React application using React Router:

1. Install React Router:

npm install react-router-dom

2. Wrap your application with the BrowserRouter component:

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

function App() {
  return (
    <BrowserRouter>
      {/* Your application code goes here */}
    </BrowserRouter>
  );
}

3. Define your routes using the Route component:

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

function App() {
  return (
    <BrowserRouter>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </BrowserRouter>
  );
}

In this example, we've defined three routes using the Route component. The exact prop is used on the first route to ensure that it matches only the exact path (/), and not any paths that start with /.

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

function App() {
  return (
    <div>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/contact">Contact</Link></li>
        </ul>
      </nav>

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </div>
  );
}

Conclusion :

In this example, we've added a navigation menu using the Link component to navigate between the defined routes. The to prop is used to specify the destination route.

That's it! With these steps, you should now have a basic routing system set up in your React application using React Router.

Support Me

Join me on Codementor for more helpful tips. Make sure to like and Follow to stay in the loop with my latest articles on different topics including programming tips & tricks, tools, Framework, Latest Technologies updates.

Please support me on PATREON on below link.

Support me on Patreon

Thank you very much for supporting me.
I would love to see you in the followers list on code mentor.

Stay tuned and stay updated!
Stay Safe ! Stay Blessed !

Discover and read more posts from Rizwan
get started
post commentsBe the first to share your opinion
Show more replies