loading

React Props


Props are arguments supplied to React components.

Props are supplied to components via HTML attributes.

Props stands for properties.


React Props

React Props are similar to function arguments in JavaScript and attributes in HTML.

To add props to a component, use the same syntax as HTML attributes:

Example

Add the “brand” attribute to the Car element:

				
					const myElement = <Car brand="Ford" />;
				
			

The component accepts the argument as a props object:

Example

Use the brand attribute in the component.

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

Pass Data

Props are also used to send data from one component to another, like arguments.

Example

Transfer the “brand” attribute from the Garage to the Car component:

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

function Garage() {
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <Car brand="Ford" />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
				
			

If you want to communicate a variable rather than a string, as in the example above, simply place the variable name inside curly brackets:

Example

Create a variable called carName and pass it to the Car component:

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

function Garage() {
  const carName = "Ford";
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <Car brand={ carName } />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
				
			

Alternatively, if it were an object:

Example

Create an object called carInfo and send it to the Car component.

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

function Garage() {
  const carInfo = { name: "Ford", model: "Mustang" };
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <Car brand={ carInfo } />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
				
			
Share this Doc

React Props

Or copy link

Explore Topic