user2419831 user2419831 - 1 year ago 62
React JSX Question

ReactJS how to know which tag was click?

I created an array of buttons tag and now I want to be able to handle each button when clicked but I dont know how to handle this.handleClickSelection() in order to know which tag has been clicked.

class Search extends React.Component
{
constructor()
{
super();
this.state = { entries : [], entries_audio : [], }
}

componentWillMount()
{

$.get( 'https://something', (data) => {


var entriesArray = [];
var entriesAudioArray = [];
for (var i = 0; i < data.stories.length ; i++) {
entriesArray.push(<button className ="entries" key={i} onClick={ ()=> this.handleClickSelection() } > {data.stories[i].title }</button>);
entriesAudioArray.push( data.stories[i] );
};
this.setState( { indents : entriesArray, entries_audio : entriesAudioArray });
console.log(this.state.entries_audio);



}, 'json' );


}


handleClickSelection()
{
alert( "this particular button data");


}


//more code below

Answer Source

You can bind your click handler to the index:

... onClick={this.handleClickSelection.bind(this, i)}

and then handleClickSelection will receive the index as the first argument:

handleClickSelection(index, event) {
    console.log('item pressed: ', index);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download