0

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.

1
  • you should always update a state variable by using this.setState() method Commented Jul 1, 2019 at 17:40

2 Answers 2

1

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>
    );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Your code works but for a reason i don't know if i choose 1 then 2 it doesn't recalculate the first one (i change the class if they are more than one for the display). It keep the first one with the class A then add others with the class B. If i directly choose 2 the both will have the class B. Do you know what is happening here ? Thanks.
React does not mount component again, if it is already mounted. It will only re-render it. So when you are selecting 1 and then 2, first component is already there. So it is getting re-rendered. However, on directly selecting 2, both the components mount.
0

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
      ))}
    </>
  )
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.