DEV Community

Randy Rivera
Randy Rivera

Posted on

React: Pass State as Props to Child Components

  • A great thing about FreeCodeCamp aside from it being free it gives you like a great introduction to many different areas. In this case we're working on React. Here For example, The MyApp component is stateful and renders a Navbar component as a child. We have to pass the nameproperty in its state down to the child component, then show the name in the h1 tag that's part of the Navbar render method. name should appear after the text Hello, my name is:.

  • Ex:

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'CamperBot'
    }
  }
  render() {
    return (
       <div>
         {/* Change code below this line */}
         <Navbar name = {this.state.name}/>
         {/* Change code above this line */}
       </div>
    );
  }
};

class Navbar extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
    <div>
      {/* Change code below this line */}
      <h1>Hello, my name is: {this.props.name}</h1>
      {/* Change code above this line */}
    </div>
    );
  }
};
Enter fullscreen mode Exit fullscreen mode

Notes:

  • About React, there's an important pattern to it. The first is unidirectional data flow.
  • State flows in one direction down the tree of your application's components, from the stateful parent component to child components. The child components only receive the state data they need.
  • The second is that complex stateful apps can be broken down into just a few, or maybe a single, stateful component. The rest of your components simply receive state from the parent as props, and render a UI from that state.

Larson, Q., 2019. Frontend Development Libraries. [online] Freecodecamp.org. Available at: https://www.freecodecamp.org/learn/front-end-development-libraries/react

Top comments (0)