sir-haver
sir-haver

Reputation: 3592

How to get event.target in React WITHOUT click

I know how it can be done with onClick, for adding a new css class for example:

wheelFade = (event) => {
   event.target.classList.add('newClass');
}

render(){
    return(
       <img onClick={this.wheelFade} className="wheel1" src="wheel.png" alt=""/>
    )
   }

But if I want to add a class to the img tag using a setTimtOut for example how can I access the img tag without having the event.target that I do get on click?

Thanks in advance

Upvotes: 0

Views: 101

Answers (1)

J Livengood
J Livengood

Reputation: 2738

References would work.

constructor(props) {
  ...
  this.image = null;
}

render() {
  return (
    <img ref={image => this.image = image} />
  )
}

Once rendered, you can access the element by using this.image

Upvotes: 1

Related Questions