DEV Community

Cover image for Passing Props in React
Maasa Kono
Maasa Kono

Posted on

Passing Props in React

Somehow, I seem to have lost access to my old blog on this topic that I had posted up through my school's website (during the program), but no sweat! Here we go again, a quick little explanation on getting started with using props in React.

What Are Props?

Props (aka "properties") in React allows us to pass values from a parent component down to a child component. The values can be any data type, from strings to functions, objects, etc.

Components cannot change their props - this can only be done externally, as the parent component changes the values passed down.

(Components also have values called state, but unlike props, state is directly initialized and managed by the component itself.)

How to Create a Prop

In order to pass props to a component, we need to add them as attributes when rendered. They are written the same way as writing attributes for an HTML tag.

const catName = "Pusheen"
<Cat name={catName} />
Enter fullscreen mode Exit fullscreen mode

With the above code, the <Cat> component now has access to a prop/value of name that is set to the string "Pusheen". The prop name can be anything, just like you can give a variable just about any name. In this case, the prop's variable name has been declared as name.

Passing Props

This is how we can access the name prop in our <Cat> component:

const Cat = (props) => {
  return (
    <div>
      My name is {props.name}.
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Be sure to pass props as an argument to the entire functional component first. When referencing a prop, it must be in curly braces.

If we are passing the prop to a class component, it will look slightly different.

class Cat extends Component {
  render() {
    <div>
      My name is {this.props.name}.
    </div>
  }
}
Enter fullscreen mode Exit fullscreen mode

Click here for the documentation on React Components and Props

I hope this helps simplify the basic usage of props!

Feel free to comment any suggestions you may have to help improve this post. ( ^_^ )

Top comments (2)

Collapse
 
jacobmgevans profile image
Jacob Evans

Concise and comprehensible 😁

Collapse
 
maasak profile image
Maasa Kono

Oh good! I appreciate hearing that. :)