Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - trigger event even if the same option is selected from select dropdown

How do I fire an event when an option is selected from dropdown in ReactJS. Currently I am using onChange but I need to fire an event even if same option is selected again.

Current code:

<select name="select1" onChange={this.onChangeOption}>
    <option value='A'>Please select A...</option>
    <option value='B'>Please select B...</option>
    <option value='C'>Please select C...</option>
    <option value='D'>Please select D...</option>
</select>

I even tried adding onClick handler to option but that does not fire on click over the options as it works only with elements.

I know there are solutions using jquery by binding click event with option element, but need a solution in React. Dont want to include jQuery for only this requirement.

like image 502
Peter Avatar asked Sep 15 '17 05:09

Peter


1 Answers

This is trick, but if you need to fire function with the all changes, even with change of the same option, only one solution I know - use onClick and its detail:

class Select extends React.Component{
    onChangeOption(e){
        if (e.detail === 0){
            console.log(e.target.value);
        }
    }
    render(){
        return (
            <select name="select1" onClick={this.onChangeOption}>
                <option value='A'>Please select A...</option>
                <option value='B'>Please select B...</option>
                <option value='C'>Please select C...</option>
                <option value='D'>Please select D...</option>
            </select>
        )
    }
}

https://jsfiddle.net/69z2wepo/86140/

like image 81
Andrew Avatar answered Oct 13 '22 09:10

Andrew