In React, Props (properties) is a mechanism for passing data from parent components to child components. Props are read-only, and child components cannot modify them directly. Instead, they should be managed and updated by the parent component.
The main difference between state and props is that **props** are immutable, while state can change based on user interaction. This is why some container components need to define state to update and modify data. Child components can only pass data through props.
* * *
## Using Props
Passing Props Syntax:
The following example demonstrates how to use props in components:
## React Instance
function HelloMessage(props){return
Hello{props.name}!
; }const element = ; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element);
[Try it Β»](#)
In the example, the name property is accessed through props.name.
* * *
## Default Props
You can set default values for props through the defaultProps property of the component class, as shown in the following example:
## React Instance
class HelloMessage extends React.Component{render(){return(
Hello, {this.props.name}
); }}HelloMessage.defaultProps = {name: 'Tutorial'}; const element = ; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element);
[Try it Β»](#)
### Multiple Props
Multiple properties can be passed to child components.
## Instance
const UserCard =(props)=>{
return(
{props.name}
Age:{props.age}
Location:{props.location}
);
};
const App =()=>{
return(
);
};
ReactDOM.render(, document.getElementById('root'));
### propTypes Validation
propTypes is a tool provided by React for type checking props in components.
You can use the prop-types library to perform type checking on component props.
In React, propTypes is defined as a static property of the component. First, you need to install the prop-types package:
npm install prop-types
Then, import prop-types in your component file and define the propTypes property. Here's an example:
## Instance
import PropTypes from 'prop-types';
const Greeting =(props)=>{
return
{/* // This line will cause a console warning because name is required */}
);
};
ReactDOM.render(, document.getElementById('root'));
### Passing Callback Functions as Props
Functions can be passed as props to child components, and child components can call these functions to communicate with the parent component.
## Instance
class ParentComponent extends React.Component{
constructor(props){
super(props);
this.state={ message:''};
}
handleMessage =(msg)=>{
this.setState({ message: msg });
};
render(){
return(
);
};
ReactDOM.render(, document.getElementById('root'));
### Destructuring Props
In function components, you can simplify code by destructuring props.
## Instance
const Greeting =({ name })=>{
return