April Henig
April Henig

Reputation: 47

Is this a correct way to pass props from child to parent?

Many times, when I want to apply proper encapsulation, i.e storing form input fields data at a form component and later sending the data via an ajax call in my main component where I store the main state of the application instead of storing everything on a single component, I encounter this dilemma: Either write it all in a single component (form and ajax call), or split the work to different encapsulated components while transferring the state / props via a function callback. hence my question - is this a "correct" way to move the props up to the parent component? (In this example, just to keep it simple - logging the data from the child component via the parent component) If not, what would be a better way? Thanks in advance!

function Parent() {
  function getChildData(data) {
    console.log(data);
  }
  return <Child childData={getChildData} />;
}

function Child(props) {
  return <button onClick={sendChildData}>Update Parent's State!</button>;

  function sendChildData() {
    let data = "Data from child component!";
    props.childData(data);
  }
}

Upvotes: 2

Views: 242

Answers (1)

Or Assayag
Or Assayag

Reputation: 6336

Parent.jsx

const [childData, setChildData] = useState(null);

const Parent = () => {
  const handleData = (data) => {
    console.log(data);
    setChildData(data);
  }
  return <Child onHandleData={handleData} />;
}

Child.jsx

const Child = (props) => {
  const { onHandleData } = props;

  return <button onClick={onHandleData("Data from child component!")}>Update Parent's State!</button>;
}

Upvotes: 1

Related Questions