React-select: onChange doesn't trigger when state updated

Created on 2 Feb 2019  Â·  11Comments  Â·  Source: JedWatson/react-select

Hi,

Thanks for the react-select!

I googled and I found nothing, so I opened this issue and I don't know if this is an issue or not.

In Select2 world, triggering onChange is simple as this:

$('select').val('NEW_VALUE').trigger('change');

I think react-select is the replacement to select2 for react developers.

Is there any way to do the same with react-select?

class MyCom extends Component {
    constructor(){
        this.items = [{ label: 'one', value: 1} , { label: 'two', value: 2} ];
        this.state = { 
            selected: { label: 'one', value: 1}         
        };
    }

    handleChange(selectedValue){
        console.log(selectedValue);
    }

    someEvent() {
        // selected item will be updated after following code but handleChange doesn't trigger.
        this.setState({selected: { label: 'two', value: 2}});
    }

    render(){
        return (
            <Select
                onChange={this.handleChange}
                value={this.state.selected}
                options={this.items}
            />
        );
    }
}

Thanks.

categorquestion issureviewed

Most helpful comment

@ShivaniBali if you use markdown to format your code it would be helpful.

React Select doesn't give you JS event in its onChange _like standard html select element_, I mean you can not go for e.target.value, instead it gives you selected object. change your handleChange method like below and you are good to go:

handleChange(selectedItem) {
    this.setState({
        inputValue: selectedItem
    });
    console.log("inputValue=" + selectedItem);
}

selectedItem here is an object contains value and label.

All 11 comments

handleChange is a callback to the onChange of the Select component. It won't fire when you change the state and the value prop changes because its not a Select event, you're just changing the value it displays. At least that's how I understand it. Why not just call handleChange() in someEvent? There are a lot of issues that are bugs that need to be addressed on this library, do you mind closing this and if you still need help, asking instead on stack overflow?

I'm facing the similar issue, when I try to change the state of an element via SELECT's onChange method it does not work. What else can be used?

constructor(props) {
super(props)
this.state = {
names: [],
equipments: [],
isLoaded: false,
inputValue: 'Select Item'
};
this.handleChange = this.handleChange.bind(this);
}

handleChange(e) {
this.setState({
inputValue: e.target.value
})
console.log("inputValue=" + e.target.value);
}