简体   繁体   中英

How dynamically generate menu options for <select> from an array using React.CreateElement()

Here is the code for generating the options manually. Is there anyway to populate the options dynamically from an array or json

    return React.createElement("select", {},
      React.createElement("option", {value: "A"}, "Option A"),
      React.createElement("option", {value: "B"}, "Option B"),
      React.createElement("option", {value: "C"}, "Option C")
    );
  }

I'd highly recommend compiling JSX, and you can easily use .map where the callback returns a component:

const values = ['A', 'B', 'C'];
// ...
return (
  <select>
    {values.map(val => <option value={val}>{val}</option>)}
  </select>
);

If you can't use JSX (though you really should for anything remotely serious, since it makes syntax much easier), you can spread the result into createElement instead.

return React.createElement("select", {},
  ...values.map(value => React.createElement("option", { value }, value))
);
const values = ['A', 'B', 'C'];
// ...
return (
  <select>
    {values.map((val, i) => <option key={i} value={val}>{val}</option>)}
  </select>
);

Don't forget to add key prop as React will complain about it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM