Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically generating JSX in React

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?

like image 300
exchez Avatar asked Jun 14 '16 21:06

exchez


People also ask

How JSX is rendered in React?

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.

Can JSX be stored in a variable?

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.


1 Answers

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>
  );
}
like image 148
jaybee Avatar answered Sep 20 '22 23:09

jaybee