YouTip LogoYouTip

React Props

In React, Props (properties) are the mechanism for passing data from a parent component to a child component. Props are read-only, and child components cannot directly modify them; 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. Sub-components can only pass data through props. * * * ## Using Props Syntax for passing Props: The following example demonstrates how to use props in a component: ## React Example 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 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}

); }; const App =()=>{ return( ); }; ReactDOM.render(, document.getElementById('root')); ### propTypes Validation propTypes is a tool provided by React for type-checking a component's props. You can use the prop-types library to perform type-checking on a component's props. In React, propTypes is defined as a static property of a 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 is an example: ## Example import PropTypes from 'prop-types'; const Greeting =(props)=>{ return

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}

); } } const ChildComponent =(props)=>{ const sendMessage =()=>{ props.onMessage('Hello from Child!'); }; return(
); }; ReactDOM.render(, document.getElementById('root')); ### Destructuring Props In functional components, you can simplify your code by destructuring props. ## Example const Greeting =({ name })=>{ return

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}

)} {
← C StringsC Pointers β†’