event on click on react

0

my question is how to make an event a click pull out an item from a json in particular, that every time a click on a name appears the same name

If I click on value: 1 send me the same name in a log and I could not get it  

My code is as follows

class App extends Component {

  constructor(props){
    super(props);

    this.state = {
      names: []
    };
    
    axios.get("http://localhost:3001/names")
    .then(response => {
      this.setState({
        names: response.data
      })
    })
    .then(error => {  
      console.log(error);
    })
  }

  handleClick = (name) => {
    console.log('this is:', {name} );
  }

  render() {
    return (
      <div> 
     
        <ul>
        {
          this.state.names.map( name =>
          <li key={name} onClick={this.handleClick}>{name}</li>)
        }
        </ul>
        
    </div>
    );
  }
}
    
asked by Francisco Navarrete 29.07.2018 в 20:17
source

1 answer

1

First you need to bind the event to the component. It's kind of weird, but get used to adding events like this:

<li key={name} onClick={this.handleClick.bind(this)}>{name}</li>

The alternative to doing this is, from the constructor define the event:

constructor(props){
  super(props);

  this.state = {
    names: []
  };

  axios.get("http://localhost:3001/names")
    .then(response => {
      this.setState({
      names: response.data
    })
  })
  .then(error => {  
    console.log(error);
  })

  //Aquí:
  this.handleClick = this.handleClick.bind(this);
}
...
{/* Así puedes dejar el evento como lo tienes tú*/}
<li key={name} onClick={this.handleClick}>{name}</li>

This will only ensure that the event is correct (the handleClick function will receive event information in the name parameter). To link the data you want, you should use

<li key={name} onClick={this.handleClick.bind(this, name)}>{name}</li>

or

<li key={name} onClick={this.handleClick(name)}>{name}</li>

or using the arrow operator:

<li key={name} onClick={(e) => this.handleClick(name, e)}>{name}</li>

depending on where you prefer to do the bind .

Reference: link

    
answered by 30.07.2018 в 19:06