Curriculum
Course: React
Login

Curriculum

React

Text lesson

React Props

Props are arguments provided to React components and are passed through HTML attributes.

Props is short for properties.

React Props

React Props function like arguments in JavaScript and attributes in HTML. To pass props into a component, use the same syntax as HTML attributes.

Example

Include a “brand” attribute in the Car element:

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

The component receives the argument as a props object.

Example

Utilize the brand attribute within the component.

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

Pass Data

Props serve to transfer data between components, acting as parameters.

Example

Pass the “brand” property from the Garage component 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’re sending a variable rather than a string, simply place the variable name inside curly brackets.

Example

Define 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 />);

Or if it were an object:

Example

Create an object called carInfo and pass 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 />);
Note: React Props are immutable! Attempting to modify their value will result in an error.