Home > Web Front-end > JS Tutorial > How to Pass Props from Child to Parent in React.js?

How to Pass Props from Child to Parent in React.js?

Patricia Arquette
Release: 2024-11-15 18:23:03
Original
740 people have browsed it

How to Pass Props from Child to Parent in React.js?

Passing Props to Parent Component in React.js

Can't we send a child's props to its parent using events in React.js?

While other solutions exist, they often overlook a fundamental point. Parents already possess the props they pass to their children. So, there's no need for children to send those props back to parents.

Better Approach

Child:
The child component is kept simple.

const Child = ({ text, onClick }) => (
  <button onClick={onClick}>{text}</button>
);
Copy after login

Parent (Single Child):
Utilizing the prop it sends to the child, the parent handles the click event.

const Parent = ({ childText }) => {
  const handleClick = (event) => {
    // Parent already has the child prop.
    alert(`Child button text: ${childText}`);
    alert(`Child HTML: ${event.target.outerHTML}`);
  };

  return <Child text={childText} onClick={handleClick} />;
};
Copy after login

Parent (List of Children):
The parent manages multiple children without losing access to necessary information.

const Parent = ({ childrenData }) => {
  const handleClick = (childData, event) => {
    alert(
      `Child button data: ${childData.childText} - ${childData.childNumber}`
    );
    alert(`Child HTML: ${event.target.outerHTML}`);
  };

  return (
    <div>
      {childrenData.map((childData, index) => (
        <Child
          key={index}
          text={childData.childText}
          onClick={e => handleClick(childData, e)}
        />
      ))}
    </div>
  );
};
Copy after login

This strategy respects encapsulation and reduces coupling by avoiding reliance on the child's internal structure.

The above is the detailed content of How to Pass Props from Child to Parent in React.js?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template