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?
Specifying The React Element TypeThe first part of a JSX tag determines the type of the React element. Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.
Using JSX, you can create a function and return a set of JSX elements to a variable, and that variable used is to render the elements inside the render() function in React.
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>
  );
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With