Blog>
Snippets

Component props and VDOM re-rendering

Explain VDOM updates by creating a parent and child component communication via props.
<div id='app'></div>
This is the HTML placeholder where we will mount our React component.
/* CSS styles */
#app {
  text-align: center;
}
.child {
  color: blue;
}
.parent {
  color: red;
}
The CSS styles for our app and child components.
class ChildComponent extends React.Component {
  render() {
    // This component accepts a prop called 'message'
    return <p className='child'>{this.props.message}</p>;
  }
}
ChildComponent is a simple React component that receives a prop called 'message' and displays it.
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: 'Initial message' };
  }
  componentDidMount() {
    // After mounting, we change the state, which will re-render this component and its child.
    setTimeout(() => {
      this.setState({ message: 'Updated message from parent' });
    }, 2000);
  }
  render() {
    // The message in the state is passed down to the ChildComponent as a prop.
    return (
      <div className='parent'>
        <h1>Parent Component</h1>
        <ChildComponent message={this.state.message} />
      </div>
    );
  }
}
ParentComponent manages a piece of state called 'message' and passes it to ChildComponent as a prop. When it mounts, it updates this state, which leads to a re-render of itself and the ChildComponent with the new message prop.
ReactDOM.render(
  <ParentComponent />, // The ParentComponent to render
  document.getElementById('app') // The DOM element to mount our component into
);
Mounts the ParentComponent to the #app div, causing it to render in the page.