Home > Mobile >  Passing the value of a clicked element in a child component into a button in a parent component in r
Passing the value of a clicked element in a child component into a button in a parent component in r

Time:10-11

I have two components, a parent component and a child component. This child component is inside the parent component. Inside the child component, there's a tag that when it is clicked, a value is been stored in a separate state, Now when a button inside the parent component is clicked, the value that was stored inside a state in the child component should be printed to the console.

What I have here below


// import Checboxtest from "./Checkboxtest";
import "./styles.css";

const Child = ({ showresult, click }) => {
  const [clickedvalue, setClickedValue] = useState("");

  const ItemClicked = (e) => {
    setClickedValue("Yes");
    console.log(clickedvalue);
  };

  return (
    <div className="App">
      <h1>Checkbox Value </h1>

      <span onClick={ItemClicked}>
        <input type="checkbox" /> clik me
      </span>
    </div>
  );
};

export default function Parent() {
  const [clickedvalue, setClickedValue] = useState("");
  return (
    <div className="App">
      <h1>
        When clicked on the button below, the value of the checkbox inside the
        child component should be display on the console.
      </h1>
      <button
        onCick={() => {
          console.log(clickedvalue);
        }}
      >
        See checkbox value
      </button>
      <Child clickedvalue={clickedvalue} setClickedValue={setClickedValue} />
    </div>
  );
}

CodePudding user response:

This is known as lifting up the state. The clickedValue useState should be in the Parent component, then it should be passed onto the Child component <Child clickedValue={clickedValue}/>. And as the onClick function, in this case, is in the child component you should also pass the setter method <Child clickedValue={clickedValue} setclickedvalue={setclickedvalue}/>.

CodePudding user response:

you should lift up the state of the Child component as follow:

const Child = ({ showresult, setClickedValue }) => {
  
  const ItemClicked = (e) => {
    setclickedvalue("Yes");
    console.log(clickedvalue);
  };

  return (
    <div className="App">
      <h1>Checkbox Value </h1>

      <span onClick={ItemClicked}>
        <input type="checkbox" /> clik me
      </span>
    </div>
  );
};

export default function Parent() {
  const [clickedvalue, setclickedvalue] = useState("");

  return (
    <div className="App">
      <h1>
        When clicked on the button below, the value of the checkbox inside the
        child component should be display on the console.
      </h1>
      <button onCick={()=>{console.log(clickedvalue)}}>See checkbox value</button>
      <Child  setClickedValue = {setClickedValue}/>
    </div>
  );
}
  • Related