Demystifying 7 lesser-known React Router terms and features (With examples) 🔮
Tags: react, javascript, webdev, programming
Published: 2020-04-30 17:52:58

[Previously](https://dev.to/vaibhavkhulbe/demystifying-lesser-known-redux-terms-and-features-with-examples-112k), we talked about some of the major terms or features of React-Redux which may go unnoticed as we build or work on more and more project with the awesome UI library. 

This time though, I'm putting a few essential terms in the form of questions for React Router. As you may know, **it's a powerful routing library which helps to add new screens (pages) in your app quickly all while keeping the URL in sync with what's being displayed on the page**.

Of course, just like before, there will be definite examples for each of them!

---

![Mystery GIF](https://media.giphy.com/media/1NiMpeyTrYA00/giphy.gif)
<figcaption>Let's demystify!</figcaption>

---

## 1. How React Router differs from the `history` library? ([Doc 📃](https://reacttraining.com/react-router/web/api/history)) (◎﹏◎)

You already know what React Router is, but what is this `history` library and how is it different?

> The `history` library lets you easily manage session history anywhere JavaScript runs. It abstracts away the differences in various environments and provides a minimal API that lets you manage the history stack, navigate, and persist state between sessions.

As for, React Router, it is a _wrapper_ around `history` which handles interaction with the browser's [`window.history`](https://developer.mozilla.org/en-US/docs/Web/API/Window/history) API with its browser and hash histories. 

## 2. What is the purpose of `push()` and `replace()` methods of `history`? つ﹏⊂

#### > `push()` ([Doc 📃](https://reacttraining.com/react-router/web/api/history/push))

The `push(path, [state])` method _pushes_ a new entry onto the `history` stack.

_Example:_

```jsx
// usually all you need
<Link to="/somewhere"/>

// but you can use a location instead
const location = {
  pathname: '/somewhere',
  state: { fromDashboard: true }
}

<Link to={location}/>
<Redirect to={location}/>
history.push(location)
```
#### > `replace()` ([Doc 📃](https://reacttraining.com/react-router/web/api/history/push))

The `replace(path, [state])` method `replaces` the current entry on the `history` stack.

_Example:_

```jsx
// Continued from the above example

<Link to={location}/>
<Redirect to={location}/>
history.push(location)
history.replace(location)
```

## 3. How to get query parameters in React Router v4? ╮（╯＿╰）╭

Of course, you use the [Polyfill library](https://github.com/financial-times/polyfill-service) for old browser support but there is a recommended way to do this with the help of [`query-string`](https://github.com/sindresorhus/query-string) library. Here's how:

```javascript
const queryString = require('query-string');
const parsed = queryString.parse(props.location.search);
```
Another way can be to use the native [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) interface. Check out the following example:

```javascript
const params = new URLSearchParams(props.location.search)
const foo = params.get('name')
```

## 4. How to solve the "A Router may have only one child element" warning? ㄟ( ▔, ▔ )ㄏ

As per its [source code](https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Router.js#L53), the [`Router`](https://reacttraining.com/react-router/web/api/Router) expects `this.props.children` to be `null`. So, you have to wrap all of your `<Route />` statements inside a [`<Switch>`](https://reacttraining.com/react-router/web/api/Switch) which renders a route _exclusively_. Here's the complete solution to this:

```jsx
// Add the `Switch` import:
import { Switch, Router, Route } from 'react-router'

// Enclose all your routes inside this new `<Switch>` block:
<Router>
  <Switch>
    <Route {/* ... */} />
    <Route {/* ... */} />
  </Switch>
</Router>
``` 
For a detailed discussion check out the following question on Stackoverflow:

{% stackoverflow 42992911 %}


## 5. How to pass _params_ to `history.push()` in React Router v4? ¯\(°_o)/¯

The `history.push()` method will _push_ a new entry onto the `history` stack. While you implement navigation, you can pass the params required in the following fashion:

```javascript
this.props.history.push({
  pathname: '/template',
  search: '?query=abc', // Here
  state: { detail: response.data }
})
```

## 6. How do you implement a _default_ or _PageNotFound_ page? (°ー°〃)

Again, the `<Switch>` component will help you here. As per the documentation:

> A `<Switch>` renders the first child `<Route>` that matches. _A `<Route>` with no path always matches._

_Example:_

```jsx
<Router>
  <div>
    <Switch>
      <Route path="/" exact component={Home}/>
      <Redirect from="/old-match" to="/will-match"/>
      <Route path="/will-match" component={WillMatch}/>
      <Route component={NoMatch}/>
    </Switch>
  </div>
</Router>
```
All you need to do is add a `path` with `<Switch>` as follows:

```jsx
<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/user" component={User}/>
  <Route component={Notfound} /> 
</Switch
```

React Router documentation has an example regarding this embedded below from CodeSandbox:

[![Edit React Router - No Match (404)](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/react-router-no-match-404-es806?fontsize=14&hidenavigation=1&theme=dark)

## 7. How do you add the automatic redirect feature after login? (o_ _)ﾉ

You can use the [`<Redirect>`](https://reacttraining.com/react-router/web/api/Router) component. Rendering a `<Redirect>` will navigate to a new location. The _new_ location will override the _current_ location in the `history` stack.

```jsx
import { Redirect } from 'react-router'

export default class LoginComponent extends Component {
  render() {
    if (this.state.isLoggedIn === true) {
      return <Redirect to="/your/redirect/page" />
    } else {
      return <div>{'Login Please'}</div>
    }
  }
}
```

Watch [this video from this Scotch.io course](https://scotch.io/courses/using-react-router-4/authentication-with-redirect) on how to implement `Redirect` with authentication.

---

So, how was it? Did you find something cool? I've never implemented authentication with React Router by will definitely try it soon. What more terms or features can you demystify? The comment box is all yours!

<blockquote class="twitter-tweet" data-partner="tweetdeck"><p lang="en" dir="ltr">If these statements give you chills, don&#39;t worry! We&#39;ve all been there.<br><br>Get help with your &#39;if&#39; statements in C#: <a href="https://t.co/DjJC75vr6g">https://t.co/DjJC75vr6g</a><br><br>Image source: <a href="https://t.co/CtE0IxRwkR">https://t.co/CtE0IxRwkR</a><a href="https://twitter.com/hashtag/DevHumour?src=hash&amp;ref_src=twsrc%5Etfw">#DevHumour</a> <a href="https://twitter.com/hashtag/Programming?src=hash&amp;ref_src=twsrc%5Etfw">#Programming</a> <a href="https://twitter.com/hashtag/ICYMI?src=hash&amp;ref_src=twsrc%5Etfw">#ICYMI</a> <a href="https://t.co/ejHmFaompf">pic.twitter.com/ejHmFaompf</a></p>&mdash; Microsoft Developer UK (@msdevUK) <a href="https://twitter.com/msdevUK/status/1254357807777943552?ref_src=twsrc%5Etfw">April 26, 2020</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

---

#### [📫 Subscribe to my weekly developer newsletter 📫](https://mailchi.mp/f59beeac6b9b/devupdates)

##### PS: From this year, I've decided to write here on DEV Community. Previously, I wrote on Medium. If anyone wants to take a look at my articles, [here](https://medium.com/@vaibhavkhulbe)'s my Medium profile.