React-select: Clearing values not working

Created on 21 Nov 2017  路  2Comments  路  Source: JedWatson/react-select

Hi! First of all, thank you for developing and keeping this library. It's really helpful. Unfortunately the clearing of chosen value is not working for me and I believe this might be some kind of bug in your code.

My component is very simple:

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Select from 'react-select';
import 'react-select/dist/react-select.css';
import _ from 'lodash';

import styles from './FieldDropDown.scss';

class FieldDropDown extends Component{

    constructor(props){
        super(props);

        this.state = {
            value: null
        }
    }

    handleOnChange = (chosenValue) => {
        this.setState({
            value: chosenValue.value
        });
    };


    render(){
        const {options} = this.props;

        return (
            <Select
                name="form-field-name"
                value={this.state.value}
                options={options}
                onChange={this.handleOnChange}
                className={styles.wrapper}
            />
        );
    }
}

FieldDropDown.propTypes = {
    options: PropTypes.arrayOf(PropTypes.any)
};

export default FieldDropDown;

I can chose option, but whenever I try to use the X to delete it, I get an error saying that:

Uncaught TypeError: Cannot read property 'value' of null
    at Object.FieldDropDown._this.handleOnChange [as onChange] (bundle.js:102446)
    at Select.setValue (bundle.js:100361)
    at Select.clearValue (bundle.js:100437)
    at Object.ReactErrorUtils.invokeGuardedCallback (bundle.js:28939)
    at executeDispatch (bundle.js:28723)
    at Object.executeDispatchesInOrder (bundle.js:28743)
    at executeDispatchesAndRelease (bundle.js:24125)
    at executeDispatchesAndReleaseTopLevel (bundle.js:24136)
    at Array.forEach (<anonymous>)
    at forEachAccumulated (bundle.js:35156)

What do you think? Did I make a mistake somewhere or is it code issue?

categorquestion

Most helpful comment

It's because the handleOnChange function gets passed null when you click on the cross. I'd suggest doing something like this.

const value = chosenValue === null ? '' : chosenValue.value
this.setState({ value });

Edit: You may want to change the '' value if chosenValue is null to something else depending on what your default option is

All 2 comments

It's because the handleOnChange function gets passed null when you click on the cross. I'd suggest doing something like this.

const value = chosenValue === null ? '' : chosenValue.value
this.setState({ value });

Edit: You may want to change the '' value if chosenValue is null to something else depending on what your default option is

@jimmaaay is correct. You need to handle the null. Also I recommend that you should pass the whole choseValue to value. This will make your handleOnChange super simple.

Was this page helpful?
0 / 5 - 0 ratings