reactjs - What is the correct approach in React to loop through an array to build html-select list of items in a function and call it in render()? -


my first thought conventional way, i.e. gather data strings in function , return dangerouslysethtml. later call function {this.renderlist()} in render(). how "react way", i.e. build jsx elements in method , implement in render()? following random example of how i'd approach situation.

constructor(props) {   super(props);   this.state = {      users: [{..}, {..}, {..}],      info: [{..}, {..}]   }; }  renderselectdropdown() {     data = '<select>'      this.state.users.foreach(user =>     {            data +=  '<optgroup label={user.title}>';         (let item in this.state.info)         {             this.state.info[user.name][item].foreach(s => {                 data += '<option>'+ s +'</option>';             })         }         data += '</optgroup>'     });      data += '</select>';      return {__html: data}; }  render() {     return (          <div>             <input type="text" name="name">             <div dangerouslysetinnerhtml = this.renderselectdropdown()></div>         </div>     ) } 

try this:

renderselectdropdown() {     let list = [];      this.state.users.foreach((user, idx) =>     {            let opt = this.state.info.map((item) => {             this.state.info[user.name][item].map((s, key) => {                 <option key={key}>{s}</option>;             })         });          list.push(<optgroup key={idx} label={user.title}>{opt}</optgroup>);      });      return list; }  render() {     let list = renderselectdropdown();      return (         <div>            <input type="text" name="name">            <select>               {list}            </select>         </div>     )  } 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -