Somehow, I seem to have lost access to my old blog on this topic that I had posted up through my school's website (during the program), but no sweat! Here we go again, a quick little explanation on getting started with using props in React.
What Are Props?
Props (aka "properties") in React allows us to pass values from a parent component down to a child component. The values can be any data type, from strings to functions, objects, etc.
Components cannot change their props - this can only be done externally, as the parent component changes the values passed down.
(Components also have values called state, but unlike props, state is directly initialized and managed by the component itself.)
How to Create a Prop
In order to pass props to a component, we need to add them as attributes when rendered. They are written the same way as writing attributes for an HTML tag.
const catName = "Pusheen"
<Cat name={catName} />
With the above code, the <Cat>
component now has access to a prop/value of name
that is set to the string "Pusheen". The prop name can be anything, just like you can give a variable just about any name. In this case, the prop's variable name has been declared as name
.
Passing Props
This is how we can access the name
prop in our <Cat>
component:
const Cat = (props) => {
return (
<div>
My name is {props.name}.
</div>
)
}
Be sure to pass props
as an argument to the entire functional component first. When referencing a prop, it must be in curly braces.
If we are passing the prop to a class component, it will look slightly different.
class Cat extends Component {
render() {
<div>
My name is {this.props.name}.
</div>
}
}
Click here for the documentation on React Components and Props
I hope this helps simplify the basic usage of props!
Feel free to comment any suggestions you may have to help improve this post. ( ^_^ )
Top comments (2)
Concise and comprehensible 😁
Oh good! I appreciate hearing that. :)