React: Pass State as Props to Child Components
Randy Rivera
Posted on November 9, 2021
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 aNavbar
component as a child. We have to pass thename
property in itsstate
down to the child component, then show thename
in theh1
tag that's part of theNavbar
render method.name
should appear after the textHello, 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>
);
}
};
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
💖 💪 🙅 🚩
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.