link react router dom

Linking React Router DOM

If you are using React Router DOM for routing in your React application, you might want to link to other pages or routes within your application. Linking is done using the Link component provided by React Router DOM.

Basic Linking

To create a link in your application, simply import the Link component from React Router DOM and use it as shown below:


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

function Home() {
  return (
    <div>
      <h1>Home Page</h1>
      <Link to="/about">About</Link>
    </div>
  );
}

export default Home;

In the above example, the Link component is used to create a link to the /about route. When the user clicks on the "About" link, they will be taken to the /about route.

Linking with Parameters

If you need to pass parameters to a route, you can do so by passing an object as the second argument to the Link component. The object should contain the parameter values as key-value pairs.


function User({ match }) {
  return (
    <div>
      <h1>User ID: {match.params.id}</h1>
    </div>
  );
}

function Users() {
  return (
    <div>
      <h1>Users</h1>
      <ul>
        <li><Link to="/users/1">User 1</Link></li>
        <li><Link to="/users/2">User 2</Link></li>
        <li><Link to="/users/3">User 3</Link></li>
      </ul>
      <Route path="/users/:id" component={User} />
    </div>
  );
}

export default Users;

In the above example, the Link components are used to create links to the /users/:id route, where :id is a parameter. The parameter value is passed as part of the URL. The User component is rendered when the URL matches the /users/:id pattern, and it extracts the parameter value from the URL using the match.params object.

You can style your links using CSS just like any other element. However, you can also use the NavLink component provided by React Router DOM to add special styles to links that match the current URL.


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

function Navbar() {
  return (
    <ul>
      <li><NavLink exact to="/" activeClassName="active">Home</NavLink></li>
      <li><NavLink to="/about" activeClassName="active">About</NavLink></li>
      <li><NavLink to="/contact" activeClassName="active">Contact</NavLink></li>
    </ul>
  );
}

export default Navbar;

In the above example, the NavLink components are used to create links that add the activeClassName class to themselves when they match the current URL. This allows you to style the current link differently from the other links.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe