REACT: onChange callback not firing

Viewed 249

The onChange callback isn't firing when the user chooses a different select option. I'm using react-bootstrap as my FE component library. I've tried structuring the callback differently (ex. as a string etc.) but haven't had any luck. Thanks in advance!

JSX:

                  <Form.Group as={Col} hidden={!showSegments} controlId={segmentId} className="required">
                    <p>I am teaching in this space:</p>
                    <select ref={segmentSelect} name="segmentId" onChange={toggleSchoolBoardVisibility}>
                      { segments.map((x) => (
                          <option value={x.segmentId}>{x.name}</option>
                        )
                      )) }
                    </select>
                  </Form.Group>

JAVASCRIPT:

const toggleSchoolBoardVisibility = () => {
  console.log('hi')
}

EDIT: The onChange function is located in the same component. If I replace onChange with onBlur or onFocus, the callback gets called and works as expected.

2 Answers

This is the minimum code that works flawlessly. JS Fiddle Link.

I think you aren't using the function callback correctly.

const SelectBox = ({ options }) => {
  const onOptionSelect = (e) => {
    console.log("selected", e.target.value);
  };

  return (
    <React.Fragment>
      <select onChange={(e) => onOptionSelect(e)}>
        {options.map((opt, key) => (
          <option key={key}>{opt}</option>
        ))}
      </select>
    </React.Fragment>
  );
};

const myOptions = ["a", "b", "c", "d"];

ReactDOM.render(
  <SelectBox options={myOptions} />,
  document.getElementById("container")
);
Related