Hayk Safaryan
Hayk Safaryan

Reputation: 2046

React get specific element in JSX

So I have a jsx like this

<img
  onClick={(event) => this.handleImgClick(event)}
  id="typeLightBox"
  className={`${this.state.popupType === 'typeLightBox' ? 'selected' : ''}`}
  src="url"
/>

In the className definition I wonder if there is any way I can get the id of this specific img instead of writing the id manually?

Upvotes: 2

Views: 111

Answers (2)

md.warish Ansari
md.warish Ansari

Reputation: 137

you can use refs

`<img
 onClick={(event) => this.handleImgClick(event)}
 id="typeLightBox"
 ref={(a) => {this.image = a}}
 className={`${this.state.popupType === this.image.id ? 'selected' : ''}`}
 src="url"
/>`

but you should avoid using refs

Upvotes: -1

Tholle
Tholle

Reputation: 112777

The easiest solution would probably be to just put it in a variable:

const id = "typeLightBox";
return <img
  onClick={(event) => this.handleImgClick(event)}
  id={id}
  className={`${this.state.popupType === id ? 'selected' : ''}`}
  src="url"
/>

Upvotes: 3

Related Questions