Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use onClick event on Link: ReactJS?

In React router, I have to and onClick attributes as shown below

<li key={i}><Link to="/about" onClick={() => props.selectName(name)}>{name}</Link></li>

state = {
    selectedName: ''
};

selectName = (name) => {
   setTimeout(function(){this.setState({selectedName:name});}.bind(this),1000);
   // this.setState({selectedName: name});
}
  • to attribute navigates to about Route
  • onClick assigns value to state variable selectedName which will be displayed when navigated to About page.

When I give timeout insided function called on click, its navigating to new page and after sometime state is getting updated resulting in displaying previous name until state is updated with new name.

Is there a way where it will navigate to the new route only after the code in onClick function gets executed.

You can get the entire code [here].(https://github.com/pushkalb123/basic-react-router/blob/master/src/App.js)

like image 816
crazyCoder Avatar asked Jan 17 '18 06:01

crazyCoder


People also ask

How do you pass data onClick in react JS?

In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the sayHello function. In our example, that argument is a string: 'James': ... return ( <button onClick={() => sayHello('James')}>Greet</button> ); ...

How do you manually trigger click event in Reactjs?

To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.


1 Answers

One possible way is, Instead of using Link, use history.push to change the route dynamically. To achieve that remove the Link component and define the onClick event on li. Now first perform all the task inside onClick function and at the end use history.push to change the route means to navigate on other page.

In your case change the router inside setState callback function to ensure that it will happen only after state change.

Write it like this:

<li key={i} onClick={() => props.selectName(name)}> {name} </li>

selectName = (name) => {
    this.setState({ selectedName:name }, () => {
        this.props.history.push('about');
    });
}

Check this answers for:

When to use setState callback

How to navigate dynamically using react router dom

like image 67
Mayank Shukla Avatar answered Sep 24 '22 01:09

Mayank Shukla