DEV Community

Madhan Raj
Madhan Raj

Posted on

React Props

React Props
Props are arguments passed into React components.

Props are passed to components via HTML attributes.

props stands for properties.
React Props

React Props are like function arguments in JavaScript and attributes in HTML.

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

Add a brand attribute to the Car element:

createRoot(document.getElementById('root')).render(
  <Car brand="Ford" />
);
Enter fullscreen mode Exit fullscreen mode

The component receives the argument as a props object:
Example

Use the brand attribute in the Car component:


function Car(props) {
  return (
    <h2>I am a {props.brand}!</h2>
  );
}
Enter fullscreen mode Exit fullscreen mode

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

You can use myobj instead of props in the component:

function Car(myobj) {
  return (
    <h2>I am a {myobj.brand}!</h2>
  );
}

Enter fullscreen mode Exit fullscreen mode

Pass Multiple Properties

You can send as many properties as you want.

Every attribute is sent to the Car component as object properties.
Example

Send multiple properties to the Car component:

createRoot(document.getElementById('root')).render(
  <Car brand="Ford" model="Mustang" color="red" />
);
Enter fullscreen mode Exit fullscreen mode

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

Use the property values in the Car component:

function Car(props) {
  return (
    <h2>I am a {props.color} {props.brand} {props.model}!</h2>
  );
}
Enter fullscreen mode Exit fullscreen mode

Different Data Types

React props can be of any data type, including variables, numbers, strings, objects, arrays, and more.

Strings can be sent inside quotes as in the examples above, but numbers, variables, and objects need to be sent inside curly brackets.
Example

Numbers has to be sent inside curly brackets to be treated as numbers:

createRoot(document.getElementById('root')).render(
  <Car year={1969} />
);
Enter fullscreen mode Exit fullscreen mode

Object Props

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

Use the dot notation to access object properties:

function Car(props) {
  return (
    <>
      <h2>My {props.carinfo.name} {props.carinfo.model}!</h2>
      <p>It is {props.carinfo.color} and it is from {props.carinfo.year}!</p>
    </>
  );
}

const carInfo = {
  name: "Ford",
  model: "Mustang",
  color: "red",
  year: 1969
};

createRoot(document.getElementById('root')).render(
  <Car carinfo={carInfo} />
);



Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)