TechTeddy
TechTeddy

Reputation: 59

History prop of react router getting executed itself on page load

I am learning react router@v4 and came across an unexpected scenario while running my code. It is as follows:

I wrote below lines to navigate to another component:

<NavLink to="/data">Dummy Data</NavLink>
<Route path="/data" component={DataStore} history={history} />

In it history inside {} is a const variable referring to createBrowserHistory() of React. On DataStore page I wrote a button code with onclick function as below:

<button onClick={this.props.history.push("/")}>Back</button>

When I click Dummy Data link on main page control redirects to DataStore component and without any action it goes back to the main page after finishing page load action. Means the code specified for onClick function is executed, without clicking the button, on page load itself. To overcome this issue I wrote different function in DataStore component which I called on button click and in it I wrote "this.props.history.push('/')". I then again run my code and it worked fine.

Can anyone guide me about the above specified unusual behavior of react history function on page load. Would be very thankful for a helping response.

Upvotes: 0

Views: 507

Answers (1)

Melounek
Melounek

Reputation: 900

<button onClick={this.props.history.push("/")}>Back</button>

will be executed immediately

<button onClick={()=>this.props.history.push("/")}>Back</button>

will be executed on click

Upvotes: 1

Related Questions