Blog>
Snippets

One-Way Data Flow with Props

Emphasize the one-way data flow by updating the parent state and passing it down to the child component as a prop.
<div id="app"></div>
This is the HTML markup with a root div where our React components will be mounted.
/* CSS styles for simplicity */
.child-component {
  padding: 10px;
  border: 1px solid black;
  margin-top: 10px;
}
CSS styles for the child component to visually differentiate it from the parent.
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: 'Hello from Parent!'
    };
  }

  updateMessage = (newMessage) => {
    this.setState({ message: newMessage });
  };

  render() {
    return (
      <div>
        <button onClick={() => this.updateMessage('Updated Hello from Parent!')}>Update Message</button>
        <ChildComponent message={this.state.message} />
      </div>
    );
  }
}

const ChildComponent = (props) => (
  <div className="child-component">
    {props.message}
  </div>
);
The JavaScript code defines two React components. ParentComponent has a state that holds the message and a method to update it. It renders a button to update the state and the ChildComponent, passing the message as a prop. ChildComponent is a functional component that receives the message as a prop and displays it.
ReactDOM.render(<ParentComponent />, document.getElementById('app'));
This code renders the ParentComponent into the root div, thereby initializing the React application.