Reputation: 135
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
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