Are you ready to dive into one of the awesome concepts of ReactJS? Today, we'll talk about one of the core concepts of React: Props (which stands for properties). Don't worry; we'll keep it fun and easy to understand!
What are Props?🤔
In React, we build different components that make up our app, like building blocks. Props are like messengers that carry information from one component to another. They help components talk and share data with each other, making our app dynamic and interactive!
Passing Props: Sending Messages between Components📩
Imagine you have two friends: a Parent
and a Child
. The Parent
wants to send a message to the Child
, telling them something special. That message is like a prop!
To send the message, the Parent
simply include it as an attribute when telling the Child
to do something. For example:
// Parent.js
import React from 'react';
import Child from './Child';
const Parent = () => {
const message = 'Hello from your Parent!';
return <Child message={message} />;
};
export default Parent;
Receiving Props: The Child Listens to the Message
Now that the Parent
sent the message, how does the Child
receive it? Well, it's quite simple! The Child
just needs to listen to what the Parent
wants to say.
// Child.js
import React from 'react';
const Child = (props) => {
return <h1>{props.message}</h1>;
};
export default Child;
Modifying Props: Messages are Immutable but Adaptable!
Props are read-only, which means that you cannot change their values inside the component. If you need to change the value of a prop, you need to do it in the parent component and then pass the new value to the child component.
Making Sure the Messages are Correct with PropTypes✔️
Sometimes, we need to make sure our messages are in the right format and have all the required information. To do that, we use PropTypes! Prop types are a way to validate props that are passed to a component. Prop types can be used to ensure that the props are of the correct type and that they have the correct value.
// Child.js
import React from 'react';
import PropTypes from 'prop-types';
const Child = (props) => {
return <h1>{props.message}</h1>;
};
Child.propTypes = {
message: PropTypes.string.isRequired,
};
export default Child;
Wrapping Up!!😁
That's it! Props are like magical messengers in React. They allow our components to communicate, share information, and create awesome interactive applications!
I hope you enjoyed this human-friendly and interactive explanation of React props.
Happy coding, and keep building amazing things! 🚀