11

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.

1
  • This is not a valid attribute: option="{num}". You need <option> tags. Commented Mar 10, 2016 at 9:43

3 Answers 3

11

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>
Sign up to request clarification or add additional context in comments.

4 Comments

Ok ill try that later. Anything more simple?
@Sylar is that a joke?
@rjarmstrong I'm looking at this question in 2021 and wondering why it was even asked in the first place. Dear me!
@sylar Hey man, it's 2024 and I still found it useful :P
5

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

1 Comment

Thank you so much for this answer. While the first answer provided me a good basis, I just couldn't get my handler function to work properly. This event => handleCategoryChange(event.target.value) solved it. In my case I just had to add "event" as an argument when calling.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.