What is Props in React JS?
Props stand for properties. They make components reusable because they perform an essential function passing data from the parent component to the child component only.
Props represent objects and are immutable, which means you cannot modify them from within the component. Instead, you are meant to use and consume them. Props find application in both functional and class-based components.
Overview - Props in Javascript
Props function as a conduit for communicating between components. They empower you to create reusable and dynamic components by permitting customization of their behavior and appearance based on the data you provide.
How to Use Props in React ?
Parent Component :
Props are passed from a parent component to a child component. The parent component provides data to the child component by including attributes in the JSX tag.
import './App.css';
import Main from './Components/React-website/Main';
function App() {
return (
);
}
Child Component :
In the child component, you can access the props passed from the parent component by writing the following: the props.name , and props.age.
import React from 'react'
export default function Main(props) {
return (
Hi my name is {props.name}, age {props.age}
)
}
How to Use Props With Destructuring ?
Destructuring is a JavaScript feature that enables you to extract data from an array or object. In React, we use destructuring to unpack or extract data from our props.
We can simplify this code even further by using destructuring to extract props in child components.
import React from 'react'
export default function Main(props) {
const {name,age}=props
return (
Hi my name is {name} , age {age}
)
}
How to Set a Default Value for Props ?
You can establish default values for props in the Child Component by utilizing the defaultProps property. These values will be employed if a parent component does not supply the prop.
import React from 'react';
export default function Main(props) {
return (
My name is {props.name}, age {props.age}
);
}
Main.defaultProps = {
name: "Yash",
age: "18"
};
Recent Post
Var keyword in C#
- May 8, 2024
- 4 min read
What is Cloud Computing ? Definition &
- April 2, 2024
- 4 min read
Devika – An Open-Source AI Software Engineer
- March 27, 2024
- 3 min read