nikotromus
nikotromus

Reputation: 1054

How to create a dropdown list from a json object?

What am I doing wrong here? (probably everything). I'd like 'foo' to come up as the selection and the value when selected to be 1. The error I get is 'Objects are not valid as a React child'.

constructor(props) {
     this.state = {options: {name: 'foo', value: 1}};
  }

 render() {
    return (
        <div>
          <select>{this.state.options}</select>
        </div>
    );
}

Upvotes: 1

Views: 428

Answers (2)

GG.
GG.

Reputation: 21844

#1: You absolutely don't need to store these options in your component's state.

#2: Replace your object with an array and use Array#map to render each option.

render() {
  const options = [{ name: 'foo', value: 1 }]
  return (
    <select>
      {options.map(option =>
        <option value={option.value}>{option.name}</option>
      )}
    </select>
  )
}

Upvotes: 2

Ben Nyberg
Ben Nyberg

Reputation: 952

First of all, I think you'd want your options to be an array of objects. Then in your render function, do something like this:

constructor(props) {
  super(props);
  this.state = {options:[{name: 'foo', value: 1}]};
}
render() {
  return <div>
    <select>{this.state.options.map(function(item) {
      return <option value={item.value}>{item.name}</option>;
    })}</select></div>
}

Upvotes: 2

Related Questions