How to use props
In this post, I am going to be talking about how to use props to pass data down from the parent class in a React app through components. Also, the things you can do with that data when you get it to where you want. I am not going to really explain what component is so I am assuming you do. :) If not here is a link to the documentation.
First, what is a prop or props? The word props is short for “properties” and we use them to pass data and sometimes functions to other components in an app (in react props
is a keyword). Props allow us to pass values into our components. These values can be anything: strings, objects (including arrays and functions), and so on. They give us the opportunity to make our components more dynamic, and a lot more reusable.
Now to help explain this better let us take this scenario in and break it down
We are making some variables with some things in them that represent this person's profile. So they have a name, pic, and things. Then we pass them into the pass this info to the component using props. On line 6 we have a component called <ProfileCard/>
and in that component, we use props to take the 3 variables above to that component <ProfileCard/>
. To the right of the word ProfileCard
on line 6 we have name={name}
which is a prop that we are defining. On the left side of the = ‘name
’ is what we are calling the prop and what we are gonna use to call this prop in the <ProfileCard/>
component. And for the right side of the = we have {name}
this is the info we defined on the first code block. It is saying {name} = ‘Elon Musk”.
This is the ProfileCard this is where we are gonna use the keyword props
. On line 6 we have an h2 tag that represents where we want their name to be. The curly brackets allow us to use JavaScript. So instead of typing their name “Elon Musk” we can dynamically put that person name there (well not really dynamically because we hardcoded the name and stuff, but you get what I mean. If we had a form that takes the input of a name this is how you do it) this
refers to the object it belongs to, props
refers to the props we made name={name} pic={pic} things={things}
and then to choose which one we want to place in the h2 tag when would put .name
on the end and boom ez pz.