The Basics of Props in React

Mo Zahid
Mo Zahid
Published in
3 min readMay 30, 2021

Today we are going be talking about how to pass props down to child components within React! When transitioning from vanilla JavaScript this may be a tricky concept, hopefully the below will help move the needle in the direction of greater understanding. Buckle up, next stop props within the world of React!

Umm what was a prop again? A prop is information that is passed down from a parent component to a child component. Remember in React the children components collapse in on their parent components.

for example…

But how? What does the code actually look like? Well let’s say we need to pass an array from the Purple Rectangle component in the example above to the Green Rectangle component. Within our Purple Rectangle component our code might look something like the following.

A Parents Perspective

Right now the focal point is “<GreenRectangle array={this.array} />” which has within it a prop called array. The prop on line 16 is referencing the array on line 10 (we are using “this” because our example is a class component). Props are written within the tags of children components.

So as we can see React makes it fairly easy to pass information from parent to child. If we had multiple props the same code might look something like this…<GreenRectangle array={this.array} secondArray={this.secondArray} />. Props can be separated from each other by using a space.

A Childs Perspective

Using console.log within your child component is a nice way to double check that you have access to the prop. Line 9 is basically illustrating this check. When accessing this prop we would use “this.props.nameOfProp”. We named our prop “array” in the above example on line 16 (left side of the equal sign). So we would use “this.props.array”. If we place our prop within an h1 tag our our code would read as follows. On line 14 we are accessing our prop using curly braces because JSX needs to know that this section is Javascript.

If we look at what our code has rendered in the browser we would see this! Note: A CSS stylesheet was used to border both of our components!

Conclusion

And there you have it! Thats the basics of passing a prop down from a parent component to a child component within React! This was a pretty simplified example but keep in mind it also possible for us to pass in functions as props.

--

--