0

Trying to change state on Change using a React Select node module package, if its a regular text input it works but can't quite get this to work, returns "TypeError: event.target is undefined".

Only putting in the code that matters, not full page.


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "15",
      options: [
        { label: "Sup", value: "18" },
        { label: "Sup", value: "18" },
        { label: "Sup", value: "18" },
        { label: "Sup", value: "18" }
      ]
    };

    this.stateChange = this.stateChange.bind(this);
  }

  stateChange = event => {
    console.log(event.target.value);
    // this.setState({ value: event.target.value });
  };

  render() {
    const Home = () => {
      return (
        <Provider store={store}>
              <div className="categories">

                <Select
                  options={this.state.options}
                  onChange={this.stateChange}
                />

              </div>
2
  • A couple things: 1) What arguments does Select's onChange prop actually take? It might not be an event as you're expecting. 2) If you're defining stateChange as an arrow function. you don't need to bind it to this in the constructor. That actually does nothing due to how arrow functions are scoped. Commented Oct 21, 2019 at 1:28
  • I'm still trying to figure that event thing out with Select, and stateChange was being used differently but I changed it to this function to test this out. Commented Oct 21, 2019 at 1:32

3 Answers 3

2

If you're using the react-select library, it looks like the Select component's onChange prop will actually just give you the selected item rather than an event:

stateChange = selectedOption => {
  console.log(selectedOption);
  this.setState({ value: selectedOption });
};
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

stateChange = selectedOption => {
    console.log(`Option selected:`, selectedOption);
    this.setState({ value: selectedOption });
    // with React-Select, selectedOption is a value of option, not an event
};

Comments

1

React select onChange gives you the value directly, instead of the event, so you can simply use,

stateChange = value => {
  console.log(value);
  this.setState({ value: value });
};

React select docs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.