Search code examples
javascriptreactjsdom-eventsjsxreact-bootstrap

React Boostrap Select, First Select Option ins not triggered by onChange event


I'm using React Boostrap Select component :

  <Form.Group className="mb-1">
    <Form.Label
      htmlFor="type"
      className="iig-form-label d-inline-block text-truncate"
    >
      Type de projet &nbsp;
      {loadingTypes && <Spinner animation="grow" size="sm" />}
    </Form.Label>
    <Form.Select
      required
      aria-label="Default select example"
      id="type"
      name="type"
      onChange={(e) => handleChange(e)}
      isInvalid={false}
    >
      // THIS IS THE DEFAULT OPTION THAT IS NOT TRIGGERED    <-------------------
      <option
        value={currentType ? currentType["@id"] : ""}
        data-category={
          currentType ? currentType?.category?.label : ""
        }
      >
        {currentType
          ? currentType.label
          : `Choisir parmi la
        liste des types de projets`}
      </option>
      {filteredTypes.map((filteredTypes, key) => {
        return (
          <option
            value={`/api/types/${filteredTypes.id}`}
            data-category={filteredTypes.category.label}
            key={key}
          >
            {filteredTypes.label}
          </option>
        );
      })}

I added a default option to show.

When I click on the default option the onChange event is not triggered.

How can I fix that?


Solution

  • I couldn't follow your example, so I created a minimal example to show you how it works:

    • Create state to store the value and give the id/value of the selected option you want to see initially as default value
    • Write onChange handler
    • Pass state value and onChange handler to Form.Select
    • In Form.Select iterate over you select options list

    .

    const selectOptions = [
      { value: "js", label: "Javascript" },
      { value: "ja", label: "Java" },
      { value: "py", label: "Python" },
      { value: "go", label: "Go" },
      { value: "cs", label: "C#" }
    ];
    
    export default function App() {
      const [value, selectValue] = useState("js");
      const handleChange = (event) => selectValue(event.target.value);
      return (
        <Form.Group className="mb-1">
          <Form.Select value={value} onChange={handleChange}>
            {selectOptions.map((option) => {
              return <option value={option.value}>{option.label}</option>;
            })}
          </Form.Select>
        </Form.Group>
      );
    }
    

    https://codesandbox.io/s/dreamy-gwen-yfmw1m