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 (
  <div className="App">
   <Main name="Naveen" Age="30" />
  </div>
 );
}
				
			

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 (
  <div>
   <h3>Hi my name is {props.name}, age {props.age}</h3>
  </div>
 )
}
				
			

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 (
    <div>
        <h3>Hi my name is {name} , age {age}</h3>
    </div>
  )
}
				
			

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 (
    <div>
      <h3>My name is {props.name}, age {props.age}</h3>
    </div>
  );
}

Main.defaultProps = {
  name: "Yash",
  age: "18"
};

				
			

Leave a Reply

Your email address will not be published. Required fields are marked *