obei
obei

Reputation: 255

Get element was clicked in react using ref

I want to use react ref to get the element that was clicked, how i can do that and replace this javascript code in handleFavoritePairs function.

handleFavoritePairs = (e) => {
        const pairs = e.target.closest('.coin-start').parentNode.getAttribute('symbol');
        console.log(pairs);
}

render() {
coins[this.props.coin].map(coin => {
return (
<div className="landing-ticker-row" symbol={coin[0]} key={coin[0].toString()}>
  <div className="coin-start" onClick={this.handleFavoritePairs}>
    <i className="fas fa-star"></i>
  </div>

  <div className="coin-symbol">{coin[0]}</div>
</div>
);
})
}

Upvotes: 1

Views: 928

Answers (1)

Steve K
Steve K

Reputation: 9055

There is no reason to use ref here and it gets tricky when mapping through arrays. Just make another component and pass the symbol down to that component. Then pass your onclick function down as well. Then you can pass the symbol back up to the parent when the user clicks on it like so:

handleFavoritePairs = symbol => {
  console.log(symbol);
}

render() {
  coins[this.props.coin].map(coin => {
    return (
      <NewComponent 
        key={coin[0].toString()} 
        symbol={coin[0]} 
        handleFavoritePairs={this.handleFavoritePairs}
      />
    );
  })
}

//new component
const NewComponent = props => (
  <div className="landing-ticker-row">
    <div className="coin-start" onClick={() => props.handleFavoritePairs(props.symbol)} >
      <i className="fas fa-star"></i>
    </div>
    <div className="coin-symbol">{props.symbol}</div>
  </div>
);

As you can see you are passing the symbol down to the new component along with your handleFavoritePairs function. Then you can pass the symbol into the onclick handler in your new component and pass it back up to your main component when the user clicks on it.

Upvotes: 1

Related Questions