W
W
way_t2018-10-05 05:14:25
JavaScript
way_t, 2018-10-05 05:14:25

How to add unlimited elements in React?

It is necessary to add some html by clicking on the button. Let's say they clicked - a new input appeared. Another click - another appeared, etc.
How can this be implemented in pure React + ES6? Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2018-10-05
@way_t

Change the state of a component on button click.
#what a simple answer

S
sinneren, 2018-10-05
@sinneren

Create some input component const input =
Create a list of inputs let list_inputs = [];
On click, we add an input to list_inputs: list_inputs.push(input).
Abstractly so.

S
s-jet, 2018-10-06
@s-jet

Something like that

constructor(props) {
        super(props);
        this.state = {
          data: []
        };
};
renderInput () {
   return this.state.data.map(item => {
       return <div>
           <input type="text" value={item}/>
       </div>
   })
}

addInput () {
   let data = this.state.data;
   data.push('Новый инпут');
   this.setState({ data: data });
}

render() {
   return (<div>
       <button onClick={this.addInput.bind(this)}>Добавить</button>
       {this.renderInput()}
    </div>
    )
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question