Home > OS >  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.


// 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">
      
      <button
        onClick={()=>{console.log(clickedvalue)}}
      >
        See checkbox value
      </button>
      <Child setClickedValue={setClickedValue}  />
    </div>
  );
}

CodePudding user response:

Issue

Child never uses setClickedValue prop, it uses its own setClickedValue state update function. Child is also not passed showresult or click props.

Solution

Keep the state in the parent component and pass down the state updater function to the child. When the checkbox in the child is clicked, call the passed callback and pass the new value back to the parent.

const Child = ({ setClickedValue }) => {
  const itemClicked = (e) => {
    setClickedValue("Yes");
  };

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

      <span onClick={itemClicked}>
        <input type="checkbox" /> 
      </span>
    </div>
  );
};

export default function Parent() {
  const [clickedValue, setClickedValue] = useState("");
  
  return (
    <div className="App">
      <button
        onClick={() => { console.log(clickedValue); }}
      >
        See checkbox value
      </button>
      <Child setClickedValue={setClickedValue}  />
    </div>
  );
}

CodePudding user response:

Take one state like counter tops n parent component and pass it to child component and on change of it use useEffect and console child state on change of that state

useEffect(() => {
    console.log(<child component state here>) 
}, [props.counter]) 

Or if you want to pass that child component value to parent component you can do it like

<Child setParentState={setParentState} />

<ChildButton onClick={() => props.setParentState(<value here>) }
  • Related