Search code examples
reactjsreact-bootstrap

How can I get the value from React-Bootstrap Form-Select?


I have a React Bootstrap Form component, in which I want to get the value of a select form control. I tried to update the value of one my hooks with an onChange, but I can't seem to get it to work (type always stays as an empty string), my current code is as follows.

const [type, setType]: any = useState('');
render(
<Form.Group controlId="formBasicSelect">
     <Form.Label>Select Norm Type</Form.Label>
     <Form.Control as="select" >
        <option value="DICTUM">Dictamen</option>
        <option value="CONSTANCY">Constancia</option>
        <option value="COMPLEMENT">Complemento</option>
     value={type}
     onChange={(e: any) => setText(e.target.value)}
     </Form.Control>
 </Form.Group>
);

Similar approaches worked with other Form controls, but maybe there is something different about select.


Solution

  • value and onChange needs to be part of Form.Control (as a prop). You have put them as children and hence the issue.

    Working copy of your code is here

    Working Code Snippet

        <Form.Group controlId="formBasicSelect">
            <Form.Label>Select Norm Type</Form.Label>
            <Form.Control
              as="select"
              value={type}
              onChange={e => {
                console.log("e.target.value", e.target.value);
                setType(e.target.value);
              }}
            >
              <option value="DICTUM">Dictamen</option>
              <option value="CONSTANCY">Constancia</option>
              <option value="COMPLEMENT">Complemento</option>
            </Form.Control>
          </Form.Group>