History in React

Dasha Lary
2 min readFeb 12, 2021

One of the key elements in React is its Router. The cool thing about React Router is that it allows for dynamic routing, making almost everything in your app its component. While making my final project at Flatiron, I wanted to explore full capabilities of React Router, which prompted me to read through the entire documentation and subsequently discover a few handy features that I then successfully implemented in my application. One of such features is history.

History, or history object, refers to a major dependency of React Router and is extremely convenient when you want your app to manage your browser’s session history. History objects have many properties and methods, such as push(), which pushes a new entry onto your browser’s histor stack and essentially allows you redirect your app to a provided location, or goBack(), which does… exactly what it says it does. In order to use history in my project, I passed it down as a prop through Router to the specific components that would use it. For example, like this:

<Route exact path='/posts' render={(routerProps) => <PostList {...routerProps} posts={this.props.posts}/>}/>

Once my components had access to history, I integrated it in my forms. For instance, once a new post is created, my app automatically takes the user to the page that displays a list of all posts (including your new one), whose URL was already accessible to me as one of my Routes. This was enabled by adding the following line inside my form’s handleOnSubmit method:

this.props.history.push('/posts')

I also made a Back button, which would take a user back to the previous page. I placed this button inside my Edit Post form. This feature was super easy to implement through my handleGoBack function that would execute upon clicking the button:

handleGoBack = (e) => { this.props.history.goBack() }

These are just two simple examples of how you can use Router history in React to add functionality to your application.

I encourage everyone to learn about React Router’s history prop from its official documentation here: https://reactrouter.com/web/api/history .

--

--