2

I have the following code in React and I have no idea why it doesn't work. Basically I want it to add an instance of my component whenever the button is clicked.

addList = () => {
    return <List />
}

render() {
    return (
        <div>
            <button onClick={ this.addList }>Add new list</button>
        </div>
    );
}
0

1 Answer 1

0

The issue is that your addList function isn't rendering anything. Try setting state in your function and using the state to determine what to render in your render function.

Try this instead:

addList = () => {
  this.setState({
    showList: true,
  });
}

render() {
  const renderedList = this.state.showList === true ? <List /> : null;
  return (
    <div>
      <button onClick={ this.addList }>Add new list</button>
      {renderedList}
    </div>
  );
}

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

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.