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 = ;
The component accepts the argument as a props object:
Example
Use the brand attribute in the component.
function Car(props) {
return I am a { props.brand }!
;
}
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 I am a { props.brand }!
;
}
function Garage() {
return (
<>
Who lives in my garage?
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
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 I am a { props.brand }!
;
}
function Garage() {
const carName = "Ford";
return (
<>
Who lives in my garage?
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
Alternatively, if it were an object:
Example
Create an object called carInfo and send it to the Car component.
function Car(props) {
return I am a { props.brand.model }!
;
}
function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
Who lives in my garage?
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );