Communication between parent and child components is implemented through props in react

Article directory

  • 1. Parent component passes value to child component
    • 1. Functional components pass values through props:
    • 2. Class components pass values through props:
    • 3. An elegant way to pass multiple values at once
  • 2. Subcomponent passes value to parent component
    • 1. In function component
    • 2. In class component
  • 3. propTypes limits props

1. Parent component passes value to child component

In React, whether it is a functional component or a class component, props can be used to pass values from parent components to child components. The following are specific examples:

1. Functional components pass values through props:

// Parent component
function ParentComponent() {<!-- -->
  const message = "Hello, World!";

  return (
    <div>
      <ChildComponent message={<!-- -->message} />
    </div>
  );
}

// Subassembly
function ChildComponent(props) {<!-- -->
  return <div>{<!-- -->props.message}</div>;
}

In the above example, the parent component passes message as props to the child component ChildComponent, and the child component passes props.message >Get the value passed by the parent component and render it.

2. Class components pass values through props:

// Parent component
class ParentComponent extends React.Component {<!-- -->
  render() {<!-- -->
    const message = "Hello, World!";

    return (
      <div>
        <ChildComponent message={<!-- -->message} />
      </div>
    );
  }
}

// Subassembly
class ChildComponent extends React.Component {<!-- -->
  render() {<!-- -->
    return <div>{<!-- -->this.props.message}</div>;
  }
}

In a class component, the parent component passes the value to the child component in the form of . The child component obtains the value passed by the parent component through this.props.message.

Whether it is a functional component or a class component, there are the following points that need to be note when using props:

  • Props are read-only: In child components, the props values passed by the parent component cannot be directly modified, and they are considered immutable.
  • In functional components, the props parameter is the first parameter of the function. In class components, props are accessed through this.props.

3. An elegant way to pass multiple values at once

To pass multiple values at once, you can pass all values as an object and use destructuring assignment in the child component to receive all props at once.

For example, suppose there is a parent component Parent and a child component Child, and now you need to pass multiple values from Parent to Child:

// Parent component
import React from 'react';
import Child from './Child';

const Parent = () => {<!-- -->
  const propsData = {<!-- -->
    name: 'John',
    age: 25,
    gender: 'male',
    // More props...
  };

  return <Child {<!-- -->...propsData} />;
}

export default Parent;


// Child component
import React from 'react';

const Child = ({<!-- --> name, age, gender }) => {<!-- -->
  // Directly use destructuring assignment method to receive all props in the subcomponent
  return (
    <div>
      <p>Name: {<!-- -->name}</p>
      <p>Age: {<!-- -->age}</p>
      <p>Gender: {<!-- -->gender}</p>
      {<!-- -->/* More rendering content... */}
    </div>
  );
}

export default Child;

In the parent component Parent, define all the values to be passed in the form of object propsData, and use the extension operator {...propsData} to extend all properties to Child in the component’s props.

In the child component Child, use destructuring assignment to receive all passed props at once, and then use these props values as needed.

Doing this allows you to pass multiple values at once and accept all props at once in the child component in an elegant way.

2. Child component passes value to parent component

In React, whether it is a functional component or a class component, props can be used to transfer values from child components to parent components.

1. In function component

In functional components, you can define an event handler function in the child component and pass the event handler function to the parent component as a prop. Then in the child component, you can call the event handling function and pass the value that needs to be passed, so that the child component can pass the value to the parent component. Here is an example:

Parent component:

import React, {<!-- --> useState } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {<!-- -->
  const [value, setValue] = useState('');

  const handleChildValue = (childValue) => {<!-- -->
    setValue(childValue);
  }

  return (
    <div>
      <ChildComponent onChildValue={<!-- -->handleChildValue} />
      <p>Value from child component: {<!-- -->value}</p>
    </div>
  );
}

export default ParentComponent;

Subcomponent:

import React from 'react';

function ChildComponent(props) {<!-- -->
  const handleClick = () => {<!-- -->
    props.onChildValue('Hello from child');
  }

  return (
    <button onClick={<!-- -->handleClick}>Click Me</button>
  );
}

export default ChildComponent;

In the above example, ParentComponent implements a child component by passing the handleChildValue function to the ChildComponent component’s onChildValue prop Pass value to parent component. When the button in the child component is clicked, the handleClick function is called and props.onChildValue is called to pass the data to the parent component.

2. In class component

In class components, subcomponents can also pass values to parent components in a similar way. Here’s an example:

Parent component:

import React, {<!-- --> Component } from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends Component {<!-- -->
  constructor(props) {<!-- -->
    super(props);
    this.state = {<!-- -->
      value: ''
    };
  }

  handleChildValue = (childValue) => {<!-- -->
    this.setState({<!-- --> value: childValue });
  }

  render() {<!-- -->
    return (
      <div>
        <ChildComponent onChildValue={<!-- -->this.handleChildValue} />
        <p>Value from child component: {<!-- -->this.state.value}</p>
      </div>
    );
  }
}

export default ParentComponent;

Subcomponent:

import React from 'react';

class ChildComponent extends React.Component {<!-- -->
  handleClick = () => {<!-- -->
    this.props.onChildValue('Hello from child');
  }

  render() {<!-- -->
    return (
      <button onClick={<!-- -->this.handleClick}>Click Me</button>
    );
  }
}

export default ChildComponent;

In the above example, the parent component transfers the value from the child component to the parent component by passing the handleChildValue function to the onChildValue prop of the ChildComponent component. When the button in the child component is clicked, the handleClick function is called and props.onChildValue is called to pass the data to the parent component.

3. propTypes limit props

Since React v15.5, PropTypes has been separated as an independent package. Prior to this version, PropTypes were included directly in the react library as part of React.
PropTypes can be used in child components to limit the data type of props passed by the parent component to the child component, and can set default values. To use propTypes, you need to introduce the prop-types library first.

Here’s an example:

import React from 'react';
import PropTypes from 'prop-types';

class ChildComponent extends React.Component {<!-- -->
  render() {<!-- -->
    return (
      <div>
        <h2>{<!-- -->this.props.title}</h2>
        <p>{<!-- -->this.props.description}</p>
      </div>
    );
  }
}

ChildComponent.propTypes = {<!-- -->
  title: PropTypes.string.isRequired, // Restrict title to string type and must be passed
  description: PropTypes.string // Limit description to string type, not required
}

ChildComponent.defaultProps = {<!-- -->
  description: "No description" // Set the default value of description to "No description"
}

export default ChildComponent;

In the above example, the ChildComponent component uses propTypes to restrict the title to a string type and must be passed, and the description to a string type, but not required to be passed. If the parent component does not pass a title, or the passed type is not a string, you will receive a corresponding warning in the console.

In addition, ChildComponent also uses defaultProps to set the default value of description to “No description”. This default value will be used when the parent component does not pass a description.

Example of usage when the parent component uses ChildComponent:

import React from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends React.Component {<!-- -->
  render() {<!-- -->
    return (
      <div>
        <ChildComponent title="Hello" description="This is a child component" />
      </div>
    );
  }
}

export default ParentComponent;

In the above example, ParentComponent passes title and description to ChildComponent. The title satisfies the restricted type and must-pass requirements, and the description also satisfies the restricted type.

The following are common data types and the types that PropTypes can detect:

td>

Data type Type detected by PropTypes
Number PropTypes.number
String PropTypes.string
Boolean PropTypes.bool
Array PropTypes.array
Object td>

PropTypes.object
Function PropTypes.func
Symbol PropTypes.symbol
Element type PropTypes.element
Any type PropTypes.any
Custom type PropTypes.instanceOf(MyClass)
A set of types PropTypes.oneOfType([PropTypes.number, PropTypes.string])
Limit optional values PropTypes.oneOf([‘red’, ‘blue’])
Restrict arrays of specific types PropTypes.arrayOf(PropTypes.number )
Restrict objects of specific types PropTypes.objectOf(PropTypes.number)
Restrictions The object has specific properties PropTypes.shape({ name: PropTypes.string, age: PropTypes.number })