Understanding React Routing and it's Concepts

Routing is a very common and needless to say a very important concept in react. In react we are made to understand that websites( built with react ) are made largely with JavaScript as opposed to traditional websites that are very HTML heavy. These ‘pages' in react get rendered or removed on or from the DOM( Document Object Module ) depending on the choices or actions we make or take.

To get to these pages that are no longer rendered on the Dom we use routing .

THE SETUP.

As most concepts in react, we start by installing the react-router-dom library ( there are many libraries for routing, but react-router-dom is by far the most popular and therefore the library we shall focus on in this article ).

1.

npx install  --save react-router-dom

Or

yarn add react-router-dom
  1. We import Browser Router in our index.js file which allows us use the routing in our App.js file. We can leverage the Browser Router by wrapping the App.js component in it.
Import { BrowserRouter } from ‘react-router-dom’;

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>, 
    document.getElementById('root')
)

THE CONCEPTS AND IT'S USES

Now that we are all ( not really all ) setup we can use routing in our app.

Route

This would be the most used concept in your routing career ( unless of course a new concept comes along ) . The Route component renders a component( a piece of the website ) depending on the path of the url.

Example:

//app.js

Import { Route } from ‘react-router-dom’;
Import Homepage from ‘homepage';
Import About from ‘about';

function App(){
  return(
  <div>
  <Route exact path='/' component = {Homepage} />
  <Route  path='/about' component={About} />
  </div>
  )
};
export default App;

In the example above, the route renders the Homepage component we imported, if the path( of the url ) is “ / “ . The slash represents the root path, for example localhost:3000 is at the / path.

We use another route to render the about page when the path is at “/about". E.g. at localhost:3000/about or fakewebsite.com/about.

The catch however is that the website would render both the about and the homepage as the about page's route path also has a slash in it.

We work things out using the exact property.

  • Using the exact property:

The exact property tells react to render a component when the path is EXACTLY the path stated. With this exact property the issue with rendering both the about and homepage would not occur.

Example:

< Route exact path = ‘/’ component = { Homepage } >
< Route exact path = ‘/about' component = { About } >

This renders the Homepage and only the Homepage when the path corresponds with the path stated, same thing applies to the About page.

The Switch.

The Switch component( wrapped around the routes ) tells react to stop searching for more paths once it has found a match.

Example:

Import { Switch, Route } from ‘react-router-dom’;
 Import Homepage from ‘homepage';
 Import About from ‘about';

<Switch> 
      <Route path= ‘/’ component= { Homepage } >
       <Route path= ‘/about' component = { About } >
</Switch >

In the example above even when the path is /about react will only render the Homepage because the slash in the about path matches with the Homepage's ( because there is no exact) and renders that and only that.

LINK

As we’ve learnt about the url paths previously, we both know that nobody ever goes to the actual url in the browser’s search bar to navigate through a website, that’s where link comes in handy.

Example:

<Link to ‘/’ > Homepage </Link >

This Link imitates a traditional anchor tag, this gives us Homepage that when clicked on would render the actual homepage component .

ARGUMENTS WE CAN LEVERAGE WITH THE ROUTE.

One of the best things about the route is that any component you render using the route gets passed 3 arguments.

These are arguments are: • match • history • location

To check this out on your console we go over to our homepage component ( the one being rendered and link to by our Route and our Link respectively), and log out the properties being passed.

Import React from ‘react';
const Homepage = props => {
    console.log( props )
        return(
            <div> Homepage </div>
)
}

Arguements.jpg

This would log to the console an object with its 3 properties being, as we previously discussed ( and as shown in the image directly above ) match, history, and location, whose values are objects too!.

MATCH PROPERTY

Match.jpg

As shown in the image above, we have 4 properties of the match property object.

• IsExact: This value is a boolean( either true or false ), true only if the entire url in the browser matches the path of the webpage rendered.

• Params: This is an object of all the url parameters. The Url parameters help render pages dynamically.

• Path: This shows the path react is looking for to match.

• Url: It’s value is that of our component that it got rendered up to from the route. It returns the matched part of the url.

LOCATION:

The location property has 5 properties, properties of which we shouldn’t be bothered with, as the property we would be using the most in our work with routing is the pathname property.

Location.jpg

The pathname property shows the full length of the url in the browser.

HISTORY

The history object just has a load of properties in it, most of which are hardly( tilting to never ) used in our daily react lives. The most used property of history, however is the push property, which on it's own acts a lot like the Link.

History.jpg

const Homepage = props => {
    return(
  <button onClick={() => props.history.push('/about')}>About</button>
);
};

In the example above we have a button, which when clicked on, fires an action ( history.push('/about') ) that opens up the About page ( kinda like the Link yeah? )

We however use history.push in our daily lives but most often in places that the Link will not suffice example of which is in our componentDidMount.