reactjscomponents

Passing data from child component to parent


First I get data from genders array and listing options for radio buttons and I would like to pass selected option to parent component and use that data for another purpose. How can I pass data from child to parent?

Child Component

const genders = [
  {
    id: 1,
    gender: "male",
  },
  {
    id: 2,
    gender: "female",
  },
  {
    id: 3,
    gender: "do not want to share",
  },
];

export function Gender() {
  const [genderValue, setGender] = useState(1);

  const changeGenderValue = (e) => {
    const genderInputValue = e.target.id;
    setGender(genderInputValue);
    console.log(genderInputValue);
  };
  return (
    <>
      <Form>
        {genders.map((gender, key) => (
          <Form.Check
            key={key}
            className="mb-3"
            label={gender.gender}
            name="gendersInput"
            type="radio"
            id={gender.id}
            value={genderValue}
            onChange={changeGenderValue}
          />
        ))}
      </Form>
    </>
  );
}

Parent Component

function App() {
  return (
    <>
      <Card>
        <Gender gender />
      </Card>
    </>
  );
}

Solution

  • The most common and simple way to pass data from a child component to a parent is by providing a callback that will fire whenever the Gender selection changes.

    E.g.

    function App() {
      const handleOnGenderChange = () => {
        // what needs to happen when gender changes
      }
    
      return (
        <>
          <Card>
            <Gender onGenderChange={handleOnGenderChange} />
          </Card>
        </>
      );
    }
    

    You can also read this article: https://medium.com/@ozhanli/passing-data-from-child-to-parent-components-in-react-e347ea60b1bb