8

I want to generate options from an array for a select form. This is inside a React component's render method and being transpiled with JSX.

render: function(){
    return(
        <div className="control-group">
            <select id="select-food" placeholder="Pick a food...">
                <option value="">select a food</option>
                {Object.keys(this.state.foods).forEach((food) => {
                    return (<option value={food}>{food}</option>);
                })}
            </select>
        </div>
    );
}

I can output the foods inside the forEach loop to the console with console.log() just fine, but the HTML just isn't getting generated. What am I missing here to get it to work?

2 Answers 2

9

You cannot return from inside a forEach loop. You'll want to use .map() instead, which will return a new array. More info about map here.

render: function() {
  return (
    <div className="control-group">
      <select id="select-food" placeholder="Pick a food...">
        <option value="">select a food</option>
        {Object.keys(this.state.foods).map((food) => {
          return (<option value={food}>{food}</option>);
        })}
      </select>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

-1

use map or helper function check link https://egghead.io/lessons/react-dynamically-generated-components. good place to start

render: function(){
let options = ['book', 'cat', 'dog'];

    return(
        <div className="control-group">
            <select id="select-food" placeholder="Pick a food...">
               {options.map(food => <option key={id} value={food}>{food}</option>)}
            </select>
        </div>
    );
}

another solution in my demo

renderRepository() {
let repository = this.props.repositories.find((repo)=>repo.name === this.props.params.
repo_name);
let stars = [];
for (var i = 0; i < repository.stargazers_count; i++) {
stars.push('');
}
return(
<div>
<h2>{repository.name}</h2>
<p>{repository.description}</p>
<span>{stars}</span>
</div>
);
}
render() {
if(this.props.repositories.length > 0 ){
return this.renderRepository();
} else {
return <h4>Loading...</h4>;
}
}
}

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.