0

UPDATE: this is the correct way I believe of setting multiple references per loop. If there is another way where I can use a call back function instead of this, I will add it in. Thanks

class demo2 extends React.Component {

constructor(props) {
    super(props);
    this.elements = ["Alex", "Is", "A", "Psycho"];
    this.inputRefs = [];
}

printName = (key) => {
  alert(this.inputRefs[key].innerText);
}


render() {
    return (
        <div>
            {this.elements.map((v, key) => {
                return (
                    <div>
                        <p ref={ref => (this.inputRefs[key+'-name'] = ref)}>Name 1: {v}</p>
                        <p ref={ref => (this.inputRefs[key+'-name2'] = ref)}>Name 2: {v}</p>
                        <br></br>
                        <button onClick={() => this.printName(key+'-name')}> Alert name 1 </button>
                        <button onClick={() => this.printName(key+'-name2')}> Alert name 2 </button>
                    </div>
                )
            })}
        </div>
    )
}

0 Answers0