Home > database >  How to update child state when button in parent component is clicked
How to update child state when button in parent component is clicked

Time:02-23

in child component I want to update the state when user clicked on button available in parent component and I've keep track of state value as this state is also affect by other code as well so I was thinking to use useEffect() hook but I'm not sure how to achieve it.

child component:

const [sentimentButtonValue, setSentimentButtonValue] = useState(false);

return(
<>
{sentimentButtonValue}
</>
)

parent Component:

const handelTableCardOpen = (idx) => {
// when this function call, want to update child 'sentimentButtonValue' state value
    console.log(idx);
    setSelectedRow(idx);
  };

<Button key={idx} onClick={() => handelTableCardOpen (idx)}> Click </Button>

CodePudding user response:

as others have stated, you need to life the state up, BUT JUST IN CASE you have a special case where you really need it

const Child = React.forwardRef((_, ref) => {
  const [sentimentButtonValue, setSentimentButtonValue] = React.useState(false);
  React.useImperativeHandle(ref, () => ({
    whatEver: sentimentButtonValue,
    setWhatEver: setSentimentButtonValue,
  }));
  return <>{sentimentButtonValue.toString()}</>;
});

const Parent = () => {
  const childRef = React.useRef();
  const handelTableCardOpen = () => {
    childRef.current.setWhatEver(!childRef.current.whatEver);
  };

  return (
    <>
      <button onClick={handelTableCardOpen}>Click</button>
      <Child ref={childRef} />
    </>
  );
};

CodePudding user response:

You need to lift the state from the child to the parent component, and then pass that state as a prop to the child:

const Parent = () => {
  const [sentimentButtonValue, setSentimentButtonValue] = useState(false)

  const yourFunction = () => {
    setSentimentButtonValue(newValue);
  } 

  <Button
    sentimentButtonValue={sentimentButtonValue}
    onClick={yourFunction}
  >
    Click
  </Button>
}
  • Related