Hello{props.name}!
; }const element = ; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element); [Try it Β»](#) In the example, the name attribute is accessed via props.name. * * * ## Default Props You can set default values for props using the defaultProps property of the component class, as shown in the following example: ## React Example class HelloMessage extends React.Component{render(){return(Hello, {this.props.name}
); }}HelloMessage.defaultProps = {name: ''}; const element = ; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element); [Try it Β»](#) ### Multiple Props You can pass multiple attributes to a child component. ## Example const UserCard =(props)=>{ return({props.name}
Age:{props.age}
Location:{props.location}
Hello,{props.name}!
; }; Greeting.propTypes={ name: PropTypes.string.isRequired }; const App =()=>{ return(
{/* // This line of code would cause a console warning because name is required */}
);
};
ReactDOM.render(, document.getElementById('root'));
### Passing Callback Functions as Props
You can pass functions as props to a child component, and the child component can call these functions to communicate with the parent component.
## Example
class ParentComponent extends React.Component{
constructor(props){
super(props);
this.state={ message:''};
}
handleMessage =(msg)=>{
this.setState({ message: msg });
};
render(){
return(
Message from Child:{this.state.message}
Hello,{name}!
; }; const App =()=>{ return; }; ReactDOM.render(, document.getElementById('root')); ### Summary * **Passing and Using Props**: The parent component passes data to the child component, which receives it via `props`. * **Default Props**: Use `defaultProps` to set default property values for a component. * **PropTypes Validation**: Use the `prop-types` library to type-check props. * **Passing Callback Functions**: The parent component can pass functions as props to a child component to achieve inter-component communication. * **Destructuring Props**: Destructure props in functional components to simplify code. * * * ## State and Props The following example demonstrates how to combine state and props in an application. We can set the state in the parent component and pass it to the child component using props on the child component. In the render function, we set name and site to get the data passed from the parent component. ## React Example class WebSite extends React.Component{constructor(){super(); this.state = {name: "", site: ""}}render(){return(); }}class Name extends React.Component{render(){return({this.props.name}
); }}class Link extends React.Component{render(){return({this.props.site}); }}const root = ReactDOM.createRoot(document.getElementById("root")); root.render(); [Try it Β»](#) * * * ## Props Validation React.PropTypes was moved to the **prop-types** library after React v15.5. Props validation uses **propTypes**, which ensures that our application components are used correctly. React.PropTypes provides many validators to verify that incoming data is valid. When invalid data is passed to props, the JavaScript console will throw a warning. The following example creates a Mytitle component where the title attribute is required and must be a string; non-string types are automatically converted to strings: ## React 16.4 Example var title = ""; class MyTitle extends React.Component{render(){return(Hello, {this.props.title}
); }}MyTitle.propTypes = {title: PropTypes.string}; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(); [Try it Β»](#) ## React 15.4 Example var title = ""; var MyTitle = React.createClass({propTypes: {title: React.PropTypes.string.isRequired, }, render: function(){return{this.props.title}
; }}); const root = ReactDOM.createRoot(document.getElementById("root")); root.render(); [Try it Β»](#) Of course, we can introduce more `PropTypes` validators and how to use them. Here are descriptions of some commonly used `PropTypes` validators: **Basic Data Types** * `PropTypes.string`: String * `PropTypes.number`: Number * `PropTypes.boolean`: Boolean * `PropTypes.object`: Object * `PropTypes.array`: Array * `PropTypes.func`: Function * `PropTypes.symbol`: Symbol **Special Types** * `PropTypes.node`: Any renderable content: numbers, strings, elements, or arrays (including these types) * `PropTypes.element`: React element * `PropTypes.instanceOf(Class)`: Instance of a class **Combinatorial Types** * `PropTypes.oneOf(['option1', 'option2'])`: Enum type, the value must be one of the provided options * `PropTypes.oneOfType([PropTypes.string, PropTypes.number])`: One of multiple types * `PropTypes.arrayOf(PropTypes.number)`: An array of a certain type * `PropTypes.objectOf(PropTypes.number)`: An object of a certain type * `PropTypes.shape({ key: PropTypes.string, value: PropTypes.number })`: An object with a specific shape **Others** * `PropTypes.any`: Any type * `PropTypes.exact({ key: PropTypes.string })`: An object with specific keys, and no other extra keys are allowed Here is some example code showing how to use different `PropTypes` validators: ## Example import React from 'react'; import ReactDOM from 'react-dom/client'; import PropTypes from 'prop-types'; class MyComponent extends React.Component{ static propTypes ={ title: PropTypes.string.isRequired,// Must be a string and is required age: PropTypes.number,// Optional number isAdmin: PropTypes.bool,// Optional boolean user: PropTypes.shape({// Must be an object with a specific shape name: PropTypes.string, email: PropTypes.string }), items: PropTypes.arrayOf(PropTypes.string),// Must be an array of strings callback: PropTypes.func,// Optional function children: PropTypes.node,// Optional renderable content options: PropTypes.oneOf(['option1','option2']),// Must be one of the specific values }; render(){ return({this.props.title}
{this.props.age&&Age:{this.props.age}
} {this.props.isAdmin&&Admin
} {this.props.user&&(Name:{this.props.user.name}
Email:{this.props.user.email}
YouTip