Home > Back-end >  Get Parameter Data from Child then Pass to the Parent Function (React)
Get Parameter Data from Child then Pass to the Parent Function (React)

Time:06-13

Code


Parent.js

import Child from "./Child";

export default function Parent() {
  function child(name, setName) {
    return (
      <>
        <input
          placeholder="Please Input"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </>
    );
  }

  return (
    <>
      <Child child={child()} />
    </>
  );
}

Child.js

import { useState } from "react";

export default function Child({ child }) {
  const [name, setName] = useState("");
  const [list, setList] = useState([]);

  function onSubmit(e) {
    e.preventDefault();
    if (name === "") {
      console.log("Please enter a name");
    } else {
      setList([...list, name]);
      setName("");
      console.log("Name added to List");
    }
  }

  return (
    <>
      <form onSubmit={onSubmit}>
        {child(name, setName)}
        <button type="submit">Submit</button>
      </form>
    </>
  );
}

Hi, I have been trying to get the data from the child then pass it through parent function.

So, in the child, I want it to pass through the child function so that the Parent can obtain the name, setName, and then send it back to the child so that it can be added to the list. If you have any further questions, please leave them in the comments section below and I will do my best to answer them. Thank you

Codesandbox link: https://codesandbox.io/embed/heuristic-lamarr-u6fzbd?fontsize=14&hidenavigation=1&theme=dark

CodePudding user response:

Don't invoke the method (child, in your case) while sending it as a prop

import Child from "./Child";

export default function Parent() {
  function child(name, setName) {
    return (
      <>
        <input
          placeholder="Please Input"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </>
    );
  }

  return (
    <>
      <Child child={child} />   {/* pass the child method it like this */}
    </>
  );
}
  • Related