Display input fields based on a variable number in state

Viewed 130

I have the below piece of code. I have defined a const in state called items. This is the dropdown selection. It has value 0, 1 and 2 and these indicate no. of dependents.

Once user selects this dropdown, i then update the value of selected dropdown in dependents constant using useState.

I want to display input field below this which will allow user to enter dependents age. For e.g. user selects 2 in dropdown. I want to show 2 input fields below which will allow user to enter the age of 2 dependents. Similarly, if i select 1- i should only show 1 input field. In that way it should show dynamically the number of input fields as user selects in dropdown.

Can someone please let me know how to achieve it.

function App() {
  const [items] = useState([
    { label: "0", value: "0" },
    { label: "1", value: "1" },
    { label: "2", value: "2" }
  ]);
 
  const [dependents, setDependents] = useState("0");
  return (
    <div className="App">
      Select Dependents: 
      <select onChange={e => setDependents(e.currentTarget.value)}>
      {items.map(({ label, value }) => (
       <option key={value} value={value}>
       {label}
       </option>
       ))
      }
    </select>
    </div>
  );
}


"
1 Answers

Create an array based on the selected value and map it to render the input:


  <div className="App">
      Select Dependents: 
      <select onChange={e => setDependents(e.currentTarget.value)}>
      {items.map(({ label, value }) => (
       <option key={value} value={value}>
       {label}
       </option>
       ))
      }
    </select>
     {[...Array(+dependents)].map((_,index)=>{

         return <input type="text" key={index}  />
       })
     
      }
    </div>

Note :

[...Array(number)] creates an array of undefined items with length equals to number, and +number converts a string to number like +"4" gives 4

Related