George Francis
George Francis

Reputation: 502

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.

Upvotes: 11

Views: 39039

Answers (2)

Isuru Chandrasiri
Isuru Chandrasiri

Reputation: 511

We can use event.currenTarget as well.

const [type, setType]: any = useState('');

render(
  <Form.Group controlId="formBasicSelect">
    <Form.Label>Select Norm Type</Form.Label>
    <Form.Select
      value={type}
      onChange={(e: any) => setType(e.currentTarget.value)}
    >
      <option value="DICTUM">Dictamen</option>
      <option value="CONSTANCY">Constancia</option>
      <option value="COMPLEMENT">Complemento</option>
    </Form.Select>
  </Form.Group>
);

Upvotes: 2

gdh
gdh

Reputation: 13682

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>

Upvotes: 21

Related Questions