kahjuksEi
kahjuksEi

Reputation: 135

How to pass state from child to parent by right way in React

I have a Parent component where is open/close logic for Child component. Child component has open/close logic too. But behavior of these components are incorrect, when I close child in child I can not open it again in parent. How to rewrite it by right way, may be with one whole useState?

export const Parent = () => {
  const [isChildVisible, setChildVisible] = useState(false);
  return (
    <>
      <span
        className="link"
        onClick={() => {
          setChildVisible(!isChildVisible);
        }}
      >
        Click
      </span>
      {isChildVisible && <Child />}
    </>
  );
}; 

export const Child = (props) => {
  const [isClosePopup, setIsClosePopup] = useState(false);
  return (
    <>
      {!isClosePopup && (
        <StyledChild>
          <span
            onClick={() => {
              setIsClosePopup(!isClosePopup);
            }}
          >
            X
          </span>
          Content
        </StyledChild>
      )}
    </>
  );
};```

Upvotes: 2

Views: 6462

Answers (1)

abhi patil
abhi patil

Reputation: 514

move the child states to parent and pass through the props.

export const Parent = () => {
  const [isChildVisible, setChildVisible] = useState(false);
  const [isClosePopup, setIsClosePopup] = useState(false);
  return (
    <>
      <span
        className="link"
        onClick={() => {
          setChildVisible(!isChildVisible);
        }}
      >
        Click
      </span>
      {
           isChildVisible && <Child isClosePopup={isClosePopup} 
           setIsClosePopup={setIsClosePopup}/>
}
    </>
  );
}; 

export const Child = (props) => {
  const {isClosePopup,setIsClosePopup} =props
  return (
    <>
      {!isClosePopup && (
        <StyledChild>
          <span
            onClick={() => {
              setIsClosePopup(!isClosePopup);
            }}
          >
            X
          </span>
          Content
        </StyledChild>
      )}
    </>
  );
};```

Upvotes: 3

Related Questions