sdw sdw - 4 months ago 68
React JSX Question

React: Add child element after parent component has mounted

I have a parent component with child elements. I tried to add a child element after the parent component mounted:

class Parent extends React.Component {

componentDidMount() {
this.props.children.push(<NewChildComponent/>)
}

render() {
return (
<div>
{this.props.children}
</div>
)
}

}


Can someone tell me
1. How to add a child element after a parent has mounted
2. Why the above did not work

Answer

It's not working because you are mutating the props array manually - React has no idea that it has changed. In general, you should never change props at all.

If you really want to do this, you can use setState within componentDidMount, and then render your child component through that:

class Parent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      childComponent: null
    }
  }

  componentDidMount() {
    this.setState({ childComponent: <div>Hello</div> });
  }

  render() {
    return (
      <div>
        {this.state.childComponent}
      </div>
    )
  }
}

However, there might be a better solution to whatever you're trying to do. I can't imagine many situations in which you'd want to render stuff only after the parent has mounted.