Loading lesson path
Props are arguments passed into React components. Props are passed to components via HTML attributes. props stands for properties.
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:
createRoot(document.getElementById('root')).render( <Car brand="Ford" />
);The component receives the argument as a props object:
function Car(props) {
return (
<h2>I am a {props.brand}!</h2>
);
}Example » The name of the object is props, but you can call it anything you want.
You can use myobj instead of props in the component:
function Car(myobj) {
return (
<h2>I am a {myobj.brand}!</h2>
);
}Example »
You can send as many properties as you want.
Car component as object properties.
createRoot(document.getElementById('root')).render( <Car brand="Ford" model="Mustang" color="red" />
);Car component inside the props object:
function Car(props) {
return (
<h2>I am a {props.color} {props.brand} {props.model}!</h2>
);
}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.
Numbers has to be sent inside curly brackets to be treated as numbers: createRoot(document.getElementById('root')).render(
<Car year={1969} />
);Variables has to be sent inside curly brackets:
let x = "Ford";createRoot(document.getElementById('root')).render(
<Car brand={x} />
);Objects and Arrays has to be sent inside curly brackets:
let x = [1964, 1965, 1966];
let y = {name: "Ford", model: "Mustang"};createRoot(document.getElementById('root')).render(
<Car years={x} carinfo={y} />
);