Props are how we configure and customize our React Components.
They're just like function arguments because they are function arguments!
How do we pass props to components?
Using JSX, we pass props as XML attributes:
<Pokemon name="Bulbasaur" />
Keep in mind that JSX is turned into a createElement
function call that looks like this:
React.createElement(Pokemon, { name: "Bulbasaur" })
How do we receive props?
Props are received by components as a function argument:
function Pokemon(props) { /* ... */ }
props
are always an object with all received attributes represented as key/value pairs.
In this case, props
is an object with one key/value pair: name: "Bulbasaur"
.
How do we use props in components?
Using JSX, we use curly braces ({}
) to interpolate expressions into our React Elements.
We can use object property access and call props
with the key we'd like to access — props.name
.
function Pokemon(props) {
return <h1>{props.name}</h1>
}
That's it!
Now you know how to use props
in your custom React Components!
Give it a try!
Open this CodeSandbox directly in your browser and send some props to the Pokemon
component.
Show off your Pokemon knowledge and fill this component out with some HP, abilities, whatever you like!
Follow the 🧵 on Twitter:
Subscribe on YouTube:
Top comments (0)