Written by - Saksham Jain

React Router Dom


Installation:

To install react-router-dom open the root directory of your application in the terminal and then type this command: npm i react-router-dom.
This will download the react-router-dom in your application. To check the installation just open the package.json file and in it check the dependencies it will write there with the version number.
Components of react-router-dom:
  1. Route: It is the main component of React router dom. It is used to render the content based on the pathname. To use it you need to import react from react-router-dom. It has mainly to props i.e

    1. Path: This accepts a path (in the string) that the route matches. It’s a self-closing tag. Eg:- “\” or “\about” etc.
    2. Props to render route: Route has three props to define what should be rendered when the path of the route matches. Only one should be used at a time in the route element.

      • Component: It creates new elements using React.createElement. When the path matches it returns a new element every time.
      • Render: It is similar to a component but it returns the new element for the first time after that it refreshes the same element.
      • Children: It always renders regardless of the path matches or not.

  2. Switch: When we use multiple routes together then react will render all the route components with the matched path to avoid this we use all the route components under the switch component and the switch will only render the first element with the matching path. If more than two-element have similar paths then we use “ exact” keyword to find the exact match of the link.
    Example:

    function Roster() {
        return (
          <div>
            <h2>This is a roster page!</h2>
            <Switch>
              <Route exact path='/roster' component={FullRoster}/>
              <Route path='/roster/:number' component={Player}/>
            </Switch>
          </div>
        );
      }
    

  3. Link : This component is similar to the anchor tag in the HTML except anchor reloads the page but link component do the client site rendering and don’t reloads the page that’s why it is much faster. It helps us navigate between pages without reloading. It has a prop “To” which excepts the path to which user want to navigate.
    Example

    import { Link } from 'react-router-dom'
    function Header() {
      return (
        <header>
          <nav>
            <ul>
              <li><Link to='/'>Home</Link></li>
              <li><Link to='/roster'>Roster</Link></li>
              <li><Link to='/schedule'>Schedule</Link></li>
            </ul>
          </nav>
        </header>
      );
    }
    

  4. Nav Link: It’s the same as Link except it has an extra prop i.e “activeClassName” in it we can give a class name and give css property to it and many more.