Hack to have Two Data Binding

Hack to have Two Data Binding

Table of contents

No heading

No headings in the article.

In React, passing data from a child component to its parent can be done by passing a function as a prop from the parent component to the child component. The child component can then call that function with any data that needs to be passed back to the parent.

Here's an example:

// Parent Component
import React, { useState } from "react";
import ChildComponent from "./ChildComponent";

function ParentComponent() {
  const [parentData, setParentData] = useState("");

  function handleChildData(childData) {
    setParentData(childData);
  }

  return (
    <div>
      <ChildComponent onChildData={handleChildData} />
      <p>Parent Data: {parentData}</p>
    </div>
  );
}

export default ParentComponent;

// Child Component
import React, { useState } from "react";

function ChildComponent(props) {
  const [childData, setChildData] = useState("");

  function handleInputChange(event) {
    setChildData(event.target.value);
    props.onChildData(event.target.value);
  }

  return (
    <div>
      <input type="text" value={childData} onChange={handleInputChange} />
      <p>Child Data: {childData}</p>
    </div>
  );
}

export default ChildComponent;

In this example, the ParentComponent renders a ChildComponent and passes down a function handleChildData as a prop named onChildData. The ChildComponent uses this function to pass data back to the ParentComponent when the input field is changed.

The handleChildData function is called with the childData as an argument, which is then used to update the state of the ParentComponent. This causes a re-render of the ParentComponent, and the updated parentData is displayed in the <p> tag.

This is one way to achieve "two-way data binding" in React, where data can be passed between the parent and child components in both directions. However, this approach can also lead to complex and hard-to-debug code, so it's generally recommended to keep the data flow in React as one-way as possible.