user3659739
user3659739

Reputation: 454

How can I dynamically generate components?

I want to be able to generate a certain number of components (all similar) according to a value chosen in a select element.

I tried to generate this by creating an array of components whose size is the selected number. When I select a number it launch a handle function which changes the selected number in the creation.

handle = selected => {
  this.state.number= selected.value;
  this.forceUpdate();
};

render() {
  return( 
   <Select onChange={this.handle} options = { ... }/>
   {[...Array(this.state.number)].map(e => { return ( <TestComponent /> 
); })}
  )
}

It loads the first component because the number is initialized to 1 but when I select another number 2,3,4,5,... it doesn't render the new components.

Upvotes: 0

Views: 54

Answers (2)

Dennis Vash
Dennis Vash

Reputation: 53964

You don't update the state so this.state.number value is always set to its initialized value:

handle = selected => {
  this.setState({ number: selected.value }); // Will re-render the component
  this.forceUpdate();
};

render() {
  return( 
    <>
      <Select onChange={this.handle} />
      {[...Array(this.state.number)].map((e, i) => (
        <TestComponent key={i} />
                     // ^ Add a unique key
      ))}
    </>
  )
}

Upvotes: 0

sk01
sk01

Reputation: 282

You can create a function like below:

makeComponentList=(num)=>{
    let i=0,arr=[];
    for(;i<num;i++){
        arr.push(<TestComponent key={i} />)
    }
    return arr;
}

handle = selected => {
    this.setState({number:selected.value});
}

render() {
    return(
        <React.Fragment>
            <Select onChange={this.handle} options = { ... }/>
            {this.makeComponentList(this.state.number)}
        </React.Fragment>
    );
}

Upvotes: 1

Related Questions