React: Pass State as Props to Child Components

rthefounding

Randy Rivera

Posted on November 9, 2021

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

💖 💪 🙅 🚩
rthefounding
Randy Rivera

Posted on November 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related