React Props

Props, short for properties, are arguments passed into React components. They are similar to function arguments in JavaScript and HTML attributes.




Passing Props to Components

Props are passed to components using HTML-like attributes. In this example, the type attribute is passed to the Vehicle component.

const myElement = <Vehicle type="Car" />;




Receiving Props in Components

The component receives the prop as a props object. Here’s how to use the type attribute in the component:

function Vehicle(props) {
  return <h2>This is a {props.type}.</h2>;
}

export default Vehicle;




Passing Data Between Components

Props can also be used to pass data from one component to another. Here’s an example of passing a type property from the Garage component to the Vehicle component:

function Vehicle(props) {
  return <h2>This is a {props.type}.</h2>;
}

function Garage() {
  return (
    <>
      <h1>What's in the garage?</h1>
      <Vehicle type="Car" />
    </>
  );
}

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




Using Variables as Props

If you need to pass a variable instead of a string, use curly brackets. Here’s how to send a variable named vehicleType to the Vehicle component:

function Vehicle(props) {
  return <h2>This is a {props.type}.</h2>;
}

function Garage() {
  const vehicleType = "Truck";
  return (
    <>
      <h1>What's in the garage?</h1>
      <Vehicle type={vehicleType} />
    </>
  );
}

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




Using Objects as Props

You can also pass an object as a prop. Here’s how to send an object named vehicleInfo to the Vehicle component:

function Vehicle(props) {
  return <h2>This is a {props.info.model}.</h2>;
}

function Garage() {
  const vehicleInfo = { name: "Truck", model: "Ford" };
  return (
    <>
      <h1>What's in the garage?</h1>
      <Vehicle info={vehicleInfo} />
    </>
  );
}

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

Scroll to Top