I am writing a modal component in React. The logic is simple, first pass the variable visible
as props to the component modal. Then the external component updates the state of the modal by controlling visible. But I got an issue where modal didn't turn off after the external component set visible to false, and it didn't seem like setState
was in effect.
I have provided the complete demo code, you can see the log that the visible object is not change as I set a new Object to it.
Code sandbox click to see demo
I hope you can help me look at this problem, thank you very much!
export default function () {
const [visible, setVisible] = useState(() => ({
m1: false,
m2: false,
m3: false
}));
const close = useCallback(() => {
const s = { ...visible, m1: false };
console.log("should be: ", s);
setVisible(s);
}, []);
useEffect(() => {
console.log("newVal: ", visible);
}, [visible]);
const props = {
components: [
{
component: (
<button
onClick={() => {
setVisible({ ...visible, m1: true });
}}
>
open Modal1
<Modal visible={visible.m1} close={close}>
this is a modal
</Modal>
</button>
)
}
]
};
return <IntroComponent {...props} />;
}