Sylar
Sylar

Reputation: 12072

How to create a simple React Dropdown

How do you create a very, very simple dropdown select with React? Nothing seem to work.

I have an array: var num = [1,2,3,4,5]

Function:

num(e){
 this.setState({selected: e.target.value});
}

In the render:

<select option="{num}"  value={this.state.selected} onChange={this.num} />

No error message, no nothing. I normally use npm plugin for this but I only need something basic.

Upvotes: 10

Views: 19527

Answers (3)

Yan
Yan

Reputation: 450

React doc answers this question here.

function FruitPicker() {
  const [selectedFruit, setSelectedFruit] = useState('orange'); // Declare a state variable...
  // ...
  return (
    <select
      value={selectedFruit} // ...force the select's value to match the state variable...
      onChange={e => setSelectedFruit(e.target.value)} // ... and update the state variable on any change!
    >
      <option value="apple">Apple</option>
      <option value="banana">Banana</option>
      <option value="orange">Orange</option>
    </select>
  );
}

Upvotes: 0

Chris Clements
Chris Clements

Reputation: 198

If you are learning React, I believe this gets to the heart of what you were asking. Here is the JSX:

<select name="category" value={category} onChange={event => handleCategoryChange(event.target.value)}>
            <option id="0" >Personal</option>
            <option id="1" >Work</option>
        </select>

And here is the on change handler:

  const [category, setCategory] = React.useState('');

  const handleCategoryChange = (category) => {
     setCategory(category);
     console.log(category);
 }

Upvotes: 5

Davin Tryon
Davin Tryon

Reputation: 67296

Setting option={num} will not work in jsx. You need to use <option> tags:

Something like this is what you are after:

<select name="select" onChange={this.num}>
  {num.map(function(n) { 
      return (<option value={n} selected={this.state.selected === n}>{n}</option>);
  })}
</select>

Upvotes: 9

Related Questions