React How to change state value from child to Parent using useState and useContext

Viewed 1296

I am new to react Hooks, I have one Parent component, and 2 child component, I am passing the "name" from Parent to both the child's using context, and I can get and print them in Childs. Now I need to change the name in on of the child component, so that the Parent and another child should see the changes, But I don't know how to achieve this. Here is My code

Code:

import React, { useState, useEffect } from "react";
import Child1 from "./Child1";
import Child2 from "./Child2";

export const ParentContext = React.createContext();
function Par() {
  const [name, setName] = useState("");

  useEffect(() => {
    setName("Parent Name");
  }, []);
  return (
    <div>
      <ParentContext.Provider value={name}>
        Name from Parent {name}
        <Child1 />
        <Child2 />
      </ParentContext.Provider>
    </div>
  );
}

export default Par;

import React, { useContext } from "react";
import { ParentContext } from "./Par";

function Child1() {
  const name = useContext(ParentContext);
  return <div>Name in Child1 is {name}</div>;
}

export default Child1;


import React, { useContext, useState } from "react";
import { ParentContext } from "./Par";

function Child2() {
  const name = useContext(ParentContext);

  const [newName, setNewName] = useState("");

  const onClick = () => {
     alert(newName);
  // don't know how to set this newName to the parent and another child
  };


  return (
    <div>
      Name in Child2 is {name}
      <input type="text" onChange={(e) => setNewName(e.target.value)} />
      <input type="button" value="Change Name" onClick={onClick} />
    </div>
  );
}

export default Child2;
1 Answers

You need to include the setter setName in Context Provider value too:

function Par() {
  const [name, setName] = useState("Parent Name");

  return (
    <div>
      <ParentContext.Provider value={{ name, setName }}>
        Name from Parent {name}
        <Child1 />
        <Child2 />
      </ParentContext.Provider>
    </div>
  );
}

function Child1() {
  const { name } = useContext(ParentContext);
  return (
    <>
      <div>Name in Child1 is {name}</div>
    </>
  );
}

function Child2() {
  const { name, setName } = useContext(ParentContext);
  const [newName, setNewName] = useState("");

  const onClick = () => {
    alert(newName);
    setName(newName);
  };

  return (
    <div>
      Name in Child2 is {name}
      <input type="text" onChange={(e) => setNewName(e.target.value)} />
      <input type="button" value="Change Name" onClick={onClick} />
    </div>
  );
}
Related