S
S
sinevik2018-03-21 10:19:29
React
sinevik, 2018-03-21 10:19:29

How to get the key by clicking?

click(e){
    console.log(e.altKey);
    let unit = this.state.array;
}


    
render() {
    let array = this.state.array;
    let unit = array.map((item, index) => {
                return (
                <a key={index}
                style={{display:"block"}}
                onClick={this.click.bind(this)}
                >Hello, {item}</a>
                )
            });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-03-21
@sinevik

Why do you need a key? Pass the element itself:

сlick(e, item) {
  console.log(item);
}

render() {
    const { array } = this.state;
    const unit = array.map((item, index) => (
      <a 
        key={index}
        style={{display:"block"}}
        onClick={(e) => this.click(e, item)}
      >
        Hello, {item}
      </a>
     ));

If you still need the key, then just add one more argument to the click call .

C
Coder321, 2018-03-21
@Coder321

click(e, index){
    console.log(e.altKey);
    let unit = this.state.array;
}


    
render() {
    let array = this.state.array;
    let unit = array.map((item, index) => {
                return (
                <a key={index}
                style={{display:"block"}}
                onClick={(e)=>this.click(e, index)}
                >Hello, {item}</a>
                )
            });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question