skip to Main Content

How to add input tag inside the for loop.
we had a number of 6 . so want 6 input tag show in the UI.
for that what would be the code.

render() {
return (

Team Size:

N/A
1
2
3
4

      <div>Selected value is : {this.state.selectValue}</div>
      {
        for (let i = 0; i< this.state.selectValue; i++) {
          <input type="text" />
          
        }
      }
    </div>
  </div>

2

Answers


  1. How about this?

        <div>
          <div>Selected value is : {this.state.selectValue}</div>
          {[...Array(this.state.selectValue)].map((_, i) => {
            return <input key={i} type="text" />
          })}
        </div>
    

    You may use for loop here as well instead of […Array(n)].map().

    Login or Signup to reply.
  2. import React, { Component } from 'react';
    class InputList extends Component {
     constructor(props) {
    super(props);
    this.state = {
      inputValues: ['', '', '', '', '', ''], // Initialize with 6 empty strings
    };
    }handleInputChange = (index, event) => {
    const { inputValues } = this.state;
    inputValues[index] = event.target.value;
    this.setState({ inputValues });
     };render() {
    const { inputValues } = this.state;
    
    return (
      <div>
        {inputValues.map((value, index) => (
          <input
            key={index}
            type="text"
            value={value}
            onChange={(e) => this.handleInputChange(index, e)}
          />
        ))}
      </div>
    );
      }};
    export default InputList;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search