Tube Yu
Tube Yu

Reputation: 11

Set multiple component on click button - React

I'm already develop a timer on which we can enter a name and time in seconds to start the timer.

I want now to create a button and if I click, it display another timer with name, and time in seconds.

I don't know how I can do this...

Here is the timer with the inputs... https://jsfiddle.net/q806zeps/37/

I think if I can duplicate this ReactDOM.render(<App/>, document.getElementById('timer')); but I thonk it's not possible ?

Thanks

Upvotes: 1

Views: 750

Answers (2)

Shubham
Shubham

Reputation: 2210

Please have a look at this code, hope it solves your problem.

class App extends React.Component {
constructor(props){
        super(props)
        this.state = {
         counter : 1
        }
     }
  //add timer code by oneshubh
  addTimer(){
            this.setState({counter: this.state.counter+1})
  }
  render(){ 
var timerDom = [];
  for(var i = 0;i<this.state.counter;i++){
    timerDom.push(<Wrapper />)
  }
  return (
        <div>
          {timerDom}
          <button onClick={()=>this.addTimer()} >add timer</button>
        </div>);
  }
}

Upvotes: 2

jagzviruz
jagzviruz

Reputation: 1513

You can use an array on the state of Wrapper to track the individual timers within your application.

state: {
    timers: []
}

Clicking the button, adds an object into your state with your current keys.

{
      libelle: 'Input name',
      seconds: 10
}

Iterate over this array to render you Minuteur components by passing the correct index.

Here is an updated fork of your fiddle. Creating timers using an array

Upvotes: 0

Related Questions