1

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>
    );
}
1
  • Is options going to be an array of { name, value } objects? Not really sure how the current data structure translates to options Commented Dec 20, 2016 at 19:20

2 Answers 2

2

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

3 Comments

made options an array of object and implemented your code. It doesn't bomb out anymore, but the list is empty.
Does your constructor look like this?: constructor(props) { this.state = {options: [{name: 'foo', value: 1}] }; }
Check out my latest edit, I think you need the call to super(props) in your constructor.
2

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

1 Comment

Great advice! I do NOT need to store the values in a state.

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.