I'm attempting to add a child to my react app via button and have it's value get updated via button click. When I click the button the 'hard coded' child gets updated but the child added via button isn't being updated. I'm missing something fundamental.
I tried passing props to the child assuming state updates would propagate but it isn't working. https://codepen.io/esoteric43/pen/YzLqQOb
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: "Starting",
children: []
};
}
handleClick() {
this.setState({ text: "Boom" });
}
handleAdd() {
this.setState({
children: this.state.children.concat(
<Child1 key={1} text={this.state.text}></Child1>
)
});
}
render() {
return (
<div>
<Child1 text={this.state.text}></Child1>
{this.state.children}
<button onClick={() => this.handleClick()}>Change</button>
<button onClick={() => this.handleAdd()}>Add</button>
</div>
);
}
}
class Child1 extends React.Component {
render() {
return <div>{this.props.text}</div>;
}
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<App />
);
To reproduce in the above codepen link, click add then click change. The added element is not updated. Both children should be updated when the change button is clicked.