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 otherData
in the ComponentAlternate
tag!
The output will look like this:
Code repo
available on https://github.com/joncoded/jonotype/tree/001-props
Last updated