How to create a simple React Dropdown

Viewed 13703

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.

2 Answers

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);
 }
Related