2

I want create the textfields based on the count entered by the user. I have gone through many related questions, I cannot find the result as I want.

For Example: If the user enter 5 as input.. I want to create 5 text boxes for entering 5 people Name and Mobile.

How can I achieve this?

TextField to get count

  <GridItem xs={12} sm={12} md={12}>
                      <TextField
                        id="sp_Inhouse"
                        label="Number of Pilots Available "
                        type="number"
                        fullWidth
                        className={classes.textField}
                        value={this.state.sp_Inhousecount}
                        error={!!this.state.sp_InhouseError}
                        helperText={this.state.sp_InhouseError}
                        onChange={this.handleChangeInhouse}
                        margin="normal"
                        required
                      />
                    </GridItem>

Tried adding the textboxes based on button click. It works fine. but I want the result as explained.

                    <GridItem xs={12} sm={12} md={12}>
                       <Button color="primary" onClick={this.handleCreatePilots}>
                      <AddIcon />  Add Pilots
                      </Button>
                      {this.state.inhouse.map((index) => {
                        return (
                          <div key={index}>
                          <TextField
                            id="sp_Name"

                            label="Name "
                            type="number"
                            fullWidth
                          />
 <TextField
                            id="sp_Mobile"

                            label="Name "
                            type="number"
                            fullWidth
                          />
                          </div>
                        )
                      })
                      }
                    </GridItem>
 handleCreatePilots=()=>{
    this.setState({
      inhouse:[...this.state.inhouse,'']
    })
  }
3
  • no.. inhouse: [] Commented May 30, 2019 at 7:00
  • inhouse is a different value or are you saving the total number in that state variable? Commented May 30, 2019 at 7:05
  • here it is different value Commented May 30, 2019 at 7:06

2 Answers 2

3

Loop through the number entered by the user.

const inputs = [];

for (let i = 1; i <= this.state.total; i++) {
  inputs.push(
    <input name={`input-${i}`} onChange={this.onChange} />
  )
}

Render inputs

render() {
  return (
   ....
    {inputs}
  ...
  )
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      total: 0,
      totalInput: '',
      show: false,
    };
  }

  add = () => {
    this.setState({
      total: this.state.totalInput
    })
  }

  showValues = () => {
    this.setState({
      show: true
    })
  }

  onChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value
    })
  }

  render() {

    const inputs = [];

    for (let i = 1; i <= this.state.total; i++) {
      inputs.push(
        <input name={`input-${i}`} onChange={this.onChange} />
      )
    }
    return (
      <div>
        <input onChange={(e) => this.setState({ totalInput: e.target.value})} value={this.state.totalInput}  placeholder="Enter Number" />
        <button onClick={this.add}>Add</button>
        <br />
        {inputs}
         <br />
        <button onClick={this.showValues}>Show Inputs values</button>
        { this.state.show && 
          <pre>{JSON.stringify(this.state, null, 4)}</pre>
        }
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
</script>

Sign up to request clarification or add additional context in comments.

Comments

2

Here is the solution. Other refactor may be required.

Working link https://jsfiddle.net/ogmv3wpu/1/

class Hello extends React.Component {
 constructor() {
  super();
  this.state= {
   inputSize: 0
  }
 }
 
 handleOnChange(value){
 this.setState({
 inputSize: value.target.value
 });
 }
 
 renderInputs(value){
  const inputs=[];
  for(let i=0; i<value; i++){
    inputs.push(<div key={i}><input  value={Name}}type="text" name="quantity"/></div>)
  }
  return inputs;
 }
 
  render() {
  console.log(this.state.inputSize);
    return (<div>
    <input type="number" name="quantity" min="0" max="99999" onChange={(value)=>this.handleOnChange(value)}/>
    <div>
    {this.renderInputs(this.state.inputSize)}
    </div>
    </div>
    )
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

2 Comments

Perfect.. Thank you.
Your welcome, hope you could find my answer helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.