Abdelrahman Mohsen
Abdelrahman Mohsen

Reputation: 72

Pass parameter from a function to this.setState callback function

I'm a facing a bit of a problem here. I'm trying to pass a parameter from a function to this.setState callback, but I can't figure out how is this possible.

My code looks like this:

selectHandler(event){
    this.setState({
        selectedImage: event.target
    }, (event) => {
        this.markSelectedHandler(event)
    })
}

markSelectedHandler(e){
    e.target.classList.add('active')
    if(e.target !== this.state.selectedImage && this.state.selectedImage){
        this.state.selectedImage.classList.remove('active')
        e.target.classList.add('active')
    }
}

e.target returns null, any idea why this happens ?

Upvotes: 2

Views: 4518

Answers (3)

TryingToImprove
TryingToImprove

Reputation: 7407

The event will not work async. You will need to extract the values or use e.persist() reactjs.org/docs/events.html#event-pooling

You could however say:

selectHandler(event){
    const { target } = event;

    this.setState({
        selectedImage: target
    }, () => {
        this.markSelectedHandler(target)
    })
}

markSelectedHandler(target){
    target.classList.add('active')
    if(target!== this.state.selectedImage && this.state.selectedImage){
        this.state.selectedImage.classList.remove('active')
        target.classList.add('active')
    }
}

But I will recommend against it..

To be honest, you should not add your class with DOM manipulating but instead add it in your render <img className={this.state.selectedImage === myImage ? 'active' : undefined} />

Upvotes: 3

Tripti Rawat
Tripti Rawat

Reputation: 671

Try not sending event as an argument to the callback

eg you have written

selectHandler(event){
    this.setState({
        selectedImage: event.target
    }, (event) => {
        this.markSelectedHandler(event)
    })
}

Write like this instead

selectHandler(event){
    this.setState({
        selectedImage: event.target
    }, () => {
        this.markSelectedHandler(event)
    })
}

Upvotes: 0

Davin Tryon
Davin Tryon

Reputation: 67296

You are shadowing your event in this code:

selectHandler(event){
    this.setState({
        selectedImage: event.target
    }, (event) => {
        this.markSelectedHandler(event)
    })
}

You need not to shadow, by not passing a parameter with the same name (event to the setState callback):

selectHandler(event){
    this.setState({
        selectedImage: event.target
    }, () => {
        this.markSelectedHandler(event)
    })
}

Upvotes: 1

Related Questions