Beginnerprogrammer Beginnerprogrammer - 15 days ago 7
React JSX Question

ReactJS set dynamic input value based on Object

I have an Object like this:

enter image description here

And an object like this:

const subjectQuantities = {
9: 2,
11: 1,
};


Where 9 and 11 are similar to the object
id
of first
Object
what I want to do is set the value of an input field dynamically so what I did is this:

{ Object.keys(subjects).map((item, i) => (
<li className="travelcompany-input clearfix" key={i}>
<span className="input-label">{ subjects[item].name }</span>
<div className="input-group">
{ subjects[item].id in subjectQuantities ?
<input className="form-control form-travelcompany-input" type="text" value=*DYNAMIC VALUE* min="0" max="10" />
: <p>TEST</p>
}
</div>
</li>
))}


How do I set the value of this input field dynamically based on the value of the subjectQuantities object.

Answer

If i understand your question correctly you just need to do {subjectQuantities[item]}

See your example below.

{ Object.keys(subjects).map((item, i) => (
   <li className="travelcompany-input clearfix" key={i}>
      <span className="input-label">{ subjects[item].name }</span>
         <div className="input-group">
           { subjects[item].id in subjectQuantities ?
            <input className="form-control form-travelcompany-input" type="text" value={subjectQuantities[item]} min="0" max="10" />
             : <p>TEST</p>
             }
         </div>
   </li>
))}