React Props
Props are arguments passed into React components.Props are passed to components via HTML attributes.props stands for properties.
The component receives the argument as a props object:
import { createRoot } from 'react-dom/client'
function Car(props) {
return (
<h2>I am a {props.brand}!</h2>
);
}
createRoot(document.getElementById('root')).render(
<Car brand="Ford" />
);
//I am a Ford!
You can use myobj instead of props in the component:
import { createRoot } from 'react-dom/client'
function Car(myobj) {
return (
<h2>I am a {myobj.brand}!</h2>
);
}
createRoot(document.getElementById('root')).render(
<Car brand="Ford" />
);
//I am a Ford!
function App() {
return <Greeting name="Alice" />;
}
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default App;
//Hello, Alice!
props obj
Parent Component (App.jsx)
function App() {
return <Student name="Ezhil" age={22} city="Chennai" />;
}
export default App;
Child Component (Student.jsx)
function Student(props) {
console.log(props);
return (
<>
<h2>Name: {props.name}</h2>
<h2>Age: {props.age}</h2>
<h2>City: {props.city}</h2>
</>
);
}
export default Student;
//Name: Ezhil
Age: 22
City: Chennai
Passing an Array as Props
Parent
function App() {
const fruits = ["Apple", "Mango", "Orange"];
return <FruitList fruits={fruits} />;
}
Child
function FruitList(props) {
console.log(props);
return <h1>{props.fruits[0]}</h1>;
}
//Apple
function FruitList(props) {
return (
<>
{props.fruits.map((fruit) => (
<h2>{fruit}</h2>
))}
</>
);
}
//Apple
Mango
Orange
Top comments (0)