Hello and welcome to this blog I am writing this blog as a revision for react So today we are going to re-visit a topic in react call props
So the first question is why do we need props ?
<CustomComponent name="radhe-krishna" />
prop -> name
in custom componentkey
and radhe-krishna
is valuejsx
element transpiles to object(POJO)function CustomComponent(props) {
return <div>{props.name}</div>;
}
key
as name
do you know before react we having been using props in native html elements like anchor(href),img(src)
DOM
elements ?Basic Introduction Completed!
Before learning more about props , we can have one small basic props exercise, so here you go
- open code sandbox (react environment)
- make a custom component call `Info.jsx`
- render the custom component in app
- pass basic details `firstname, lastname, age, city, profession` as a prop
- consume that information in `Info` component and display
If you did it ? Well Done! you know props If got stuck with non-string props or destructuring no worries we will cover this together, continue reading 😊
non-string props, multiple props, consuming multiple props
<Info
firstName="Dheeraj"
lastName="Purohit"
age="23"
city="Mumbai"
profession="Developer"
/>
age or any boolean props
<Info
firstName="Dheeraj"
lastName="Purohit"
age={23}
isIndian={true}
city="Mumbai"
profession="Developer"
/>
export default function App() {
const propsData = {
firstName: "Dheeraj",
lastName: "Purohit",
};
return (
<div className="App">
<Info {...propsData} />
</div>
);
}
propsData
is an object having our props valueInfo
component using object
spread operator, so simple and readable right!javaScript info for spread syntax
PAY ATTENTION!
export function Info(props) {
const {
firstName,
lastName,
age,
city,
profession,
isIndian,
} = props;
return (
<div>
<ul>
<li>{firstName}</li>
<li>{lastName}</li>
<li>{age}</li>
<li>{city}</li>
<li>{profession}</li>
<li>{isIndian ? "Indian" : "Non-Indian"}</li>
</ul>
</div>
);
}
const { firstName, lastName, age, city, profession, isIndian } = props
props.keyName.propsName
export default function App() {
const propsData = {
firstName: "Dheeraj",
lastName: "Purohit",
};
return (
<div className="App">
<Info propsData={propsData} />
</div>
);
}
key
value pairexport function Info(props) {
return (
<div>
<ul>
<li>{props.propsData.firstName}</li>
<li>{props.propsData.lastName}</li>
</ul>
</div>
);
}
props.keyName.propsName
props
is general key for accessing props propsData
is our keyName
and propsName
are firstName and lastName
Refactoring time
Ending Note!
- i might have missed some parts of props, but tried to put it here as a part of my revision
- if you find this article helpful, like, share with others who is learning react
- if you find any spelling mistake, wrong term used do let me know in comments and your feedback about this blog
Happy Coding
Jai Shri Krishna🙏💜