About React
React.JS is a popular JavaScript library used for building user interfaces. It provides a way to create reusable components and manage the state of an application. In React.JS, props (short for properties) are a way to pass data from a parent component to a child component.
About this Blog Post
In this blog post, we will be diving into the concept of props in React.JS and exploring how they are used. We will look at several examples to help you understand how props work and how to use them effectively in your applications.
What are Props in React.JS?
- In React.JS, props are the means by which a parent component can pass data to its child component.
- They are used to pass data from one component to another and are a critical part of React.JS.
- Props are read-only and cannot be modified within the child component.
- They are used to pass information, such as values, functions, or objects, from the parent component to the child component.
Example 1: Passing a Value as a Prop
In the following example, we have a parent component that passes a value as a prop to a child component. The child component then displays the value as text on the screen.
// parent component
function App() {
return (
{/* passing props as attributes*/}
<Note
id="1"
title="this is title"
content="blog is about props"
/>
);
}
// child component
function Note(props) {
return (
<div>
<h1>{props.title}</h1>
<p>{props.content}</p>
</div>
);
}
Example 2: Passing a Function as a Prop
In the following example, we have a parent component that passes a function as a prop to a child component. The child component then calls the function when a button is clicked.
// parent component
function App() {
// event handling function
const printNote = (content) => {
console.log(content);
};
return (
<Note
id="1"
title="this is title"
content="blog is about props"
onClickNote={printNote}
/>
);
}
// child component
function Note(props) {
return (
<div>
<h1>{props.title}</h1>
<p>{props.content}</p>
<button
// onclick it triggers the onClickNote which is in App.jsx
// which essentially will trigger printNote function to print the note on console.
onClick={() => {
props.onClickNote(props.content);
}}
>
// delete icon component
<DeleteIcon />
</button>
</div>
);
}
Example 3: Passing an Object as a Prop
In the following example, we have a parent component that passes an object as a prop to a child component. The child component then uses the object to display information on the screen.
// parent component
function App(){
const user = {
name: "Hiren Timbadiya",
email: "hiren@email.com"
};
return (
<Note user={user} />
);
}
// child component
function Note(props){
return (
<div>
<p>Name: {props.user.name}</p>
<p>Email: {props.user.email}</p>
</div>
);
}
Thank You for reading!! follow me for more
Top comments (2)
Thank you!!☺