React props
passing data from parent to child components
To make a parent component "talk" to a child component:
the parent component will use a special kind of attribute or property known as
props
this consists of an attribute in a JSX tag
the attribute can take on any key name with any value
the child component function will receive these
props
in its parametersits
return
JSX can then use it like a variable
For example, with an App.js
we would introduce a someData
attribute, or props
:
Then, in the Component.js
we would bring the props
in as a parameter:
To access someData
we would simply use props.someData
as shown above!
Alternate syntax
We could make things more concise in the component (let's make a separate ComponentAlternate.js
file for clarity's sake):
Notice that:
the
{someData}
parameter now has curly bracesthe keyword
props
has become redundant via JavaScript destructuring
Moving this over to App.js
The output for Component
and ComponentAlternate
will look essentially identical (except for the value passed into the someData
prop):
Passing in more than one parameter
We could also pass in another parameter (let's use our ComponentAlternate.js
file):
Then, in the App.js
file:
Note how we simply added an extra JSX attribute/prop called someNumber
in the ComponentAlternate
tag!
The output will look like this:
Using the spread operator to include all properties of an object
Instead of repetitively listing all properties of an object into a child component like in the previous code block, we could use the spread operator (...variableName
):
This becomes very handy when a variable like dataSource
has a lot more than just two properties!
Last updated