DEV Community 👩‍💻👨‍💻

Cover image for React Router - How to pass History object to a component
Krisztian Kecskes
Krisztian Kecskes

Posted on

React Router - How to pass History object to a component

I was in a middle of a project, and I didn't used React for a while. I had to solve the situation: I had got a component, which was embeded deeply in a Route component (this Route was under a Browser Router component). I needed to use history object from the Router history. I started to remember my bad adventures with old React Router and circumstantial history manipulation.

So, I was in a bad mood, when I opened the official documentation. It was a big surprise when I could solve my task in 3 minutes.

There is a magical higher-order component, that name is withRouter. It takes place in the react-router-dom package also. With its help, you can pass the whole history object to your component as properties. They contains several useful data about routing.

import React, { PureComponent } from 'react';
import { withRouter } from 'react-router-dom';

class PassToMeMyRouterHistory extends PureComponent {

  redirectToHome = () => {
   const { history } = this.props;
   if(history) history.push('/home');

  render() {
    const { history } = this.props;

        <div onClick={this.redirectToHome}>You can go to Home 🥳</div>
        <div>Oh, we did not get pathname! 🤔</div>


export default withRouter(PassToMeMyRouterHistory);

Enter fullscreen mode Exit fullscreen mode

As you can see above, after we let the withRouter component to do its job, we can easily reach the necessary data and functions in connection with history. The history object has several property, you can check it in the documentation.

Ps.: You need to handle the re-render logic in your component when you need this action, in case of location change. withRouter gives you the props but doesn't subscribe for the changes!

Top comments (16)

jasterix profile image

this was such a life saver! Do you mind explaining why this.props.history.push("/home") might result in undefined but this would work?

I think it has something to do with this line--With its help, you can pass the whole history object to your component as properties.-- but am not 100% sure.

stakutis profile image

Fantastic! This finally makes some sense to me. I spent hours trying to help someone that using we children under it vs component= and I couldn't figure out why this.props.history.push() wasn't available!!! I only/ever use component= so never saw this other approach (embedded children) and didn't suspect it.

So, in your app, if at some point you want to re-direct the user (in javascript, not a tag) to a new location, what's the best way? I do not think it is window.location= because that's a page reset, right? And if you can't get to the router history, WHAT do you do??

nateosterfeld profile image
Nate Osterfeld

I know you said this a few months ago, but in case you were still wondering haha.. the history object actually exists on the window object itself in plain old vanilla JS.

vishwanath profile image

Thanks a lot Krisztian for this!

sanamsoodan profile image
Sanamdeep Singh

This was really helpful. Thanks

sstefan0v profile image
Stefan Stefanov

You saved my asss. thanks a lot :)

miloslavcv profile image
Miloslav Cvetkovic

Thank you! You saved me from losing my mind over router redirect :) 👍

josuerodriguez98 profile image
Josué Rodríguez (He/Him)

Thanks! This helped me with a problem! Appreciate it!

jkozma81 profile image
Kozma János

It is a pity that I just found this post. This would have saved for me a day of struggle and search for solutions for my react project.😄

kozakrisz profile image
Krisztian Kecskes

Next time you can solve the problem in minutes!😃👍

cvclaravista profile image
CvClaraVista • Edited on

Valeu Mano
Muito obrigado!

brunnovianna profile image
Brunno Vianna

I was looking for this for a long time. Lots and lots of worakarounds and the solution was that simple. Thank you for this!

shubham2924 profile image

Just one word 'Amazing' !

gurutobe profile image
Abdelrhman Yousry

With this one,
i was able to fix an issue caused by referencing the component in routes using "render" not "component" prop.
Thanks a lot!

tifelaflame profile image

Thank you for this article, I'm not sure I understand this solution but I knew the reason it was undefined but not how to solve it.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

We are hiring! Do you want to be our Senior Platform Engineer? We're hiring for a Senior Platform Engineer and would love for you to apply.

Head here to learn more about who we're looking for.