Home > Blockchain >  How to add a loop resultat to a component in React?
How to add a loop resultat to a component in React?

Time:02-22

I want to add the result from the loop (what is in consol.log) to the select tag as an options.

function CustomeSelect(props) {

    const values = props.values;

    for (const entry of values) {
       console.log(`<option value=${entry[0]}>${entry[1]}</option>`)
    }    

    return (
        <div>
            <label for={props.for}>{props.title}</label>
            <select value={props.value} onChange={props.onChange} id={props.id}>


// Here I want to add `<option value=${entry[0]}>${entry[1]}</option> - what is in console.log.
                
            </select>
        </div>
    );
}

CodePudding user response:

You can use Array.prototype.map to loop through values property and for each item return an option tag like this

function CustomeSelect(props) {
    const { values } = props;

    return (<div>
        <label for={props.for}>{props.title}</label>
        <select value={props.value} onChange={props.onChange} id={props.id}>

            // Here I want to add `${entry[1]} - what is in console.log.
            {Array.from(values).map(entry => {
                return <option value={entry[0]}>{entry[1]}</option>
            })}

        </select>
    </div>);
}

CodePudding user response:

Use Array.map

return (
    <div>
        <label for={props.for}>{props.title}</label>
        <select value={props.value} onChange={props.onChange} id={props.id}>
             {values.map(entry=>
                 <option value={entry[0]}>{entry[1]}</option>
              )}
        </select>
    </div>
);

CodePudding user response:

this way it will work,

function CustomeSelect(props) {

  return (
      <div>
          <label for={props.for}>{props.title}</label>
          <select onChange={props.onChange} id={props.id}>
            
            {props.values.map(
              entry => return <option key={Math.random()} value={entry[0]}>${entry[1]}</option>
            )}

          </select>
      </div>
  );
}

CodePudding user response:

You can use map method as shown below. Remember values.map will iterate over the array and gives individual value.

function CustomeSelect(props) {

const values = props.values;
// assume const values = [ "one", "two", "three" ]


return (
    <div>
        <label for={props.for}>{props.title}</label>
         <select value={props.value} onChange={props.onChange} id={props.id}>
         {
           values.map((val , index) => (
             <option key={index} value={val}>{val}</option>
            ))
         }
        </select>
        </div>
    );
}
  • Related