DEV Community

Cover image for Props in React
vidhya murali
vidhya murali

Posted on

Props in React

React Props

  • props stands for properties.
  • Props are arguments passed into React components.
  • Props are passed to components via HTML attributes.

Note: React Props are read-only! You will get an error if you try to change their value.

To send props into a component, use the same syntax as HTML attributes:

The component receives the argument as a props object:

note : The name of the object is props, but you can call it anything you want.

Pass Multiple Properties

  • You can send as many properties as you want.
  • Every attribute is sent to the Car component as object properties.

All properties are received in the Car component inside the props object:

Another Example;

output:

Object Props

The component treats objects like objects, and you can use the dot notation to access the properties.

Array Props
Array props can be accessed using the indexes.

Pass Props from Component to Component

Attributes are also how you pass data from one component to another, as parameters.

React Destructuring Props

You can limit the properties a component receives by using destructuring.

Note: React uses curly brackets to destructure props: {color}.

You can also destruct the properties you need inside the component.

This way, the component receives all the properties, but the destructuring makes sure it only uses the ones it needs.

Destructuring ...rest

When you don't know how many properties you will receive, you can use the ...rest operator.

Meaning: you can specify the properties you need, and the rest will be stored in an object.

Default Values

With Destructuring, you can set default values for props.

If a property has no value, the default value will be used.

Reference : https://www.w3schools.com/react/react_props_destructuring.asp

Top comments (2)

Collapse
 
karthick_07 profile image
Karthick (k)

Well done

Collapse
 
vidhya_murali_5aabe7784bd profile image
vidhya murali

Thank you