I am new to React and am trying to add a text editor to a pop up component with a props like visibility. Idea is to make it a component that change its visibility by prop value. I tried to use useEffect to change the state from props, however, visibility does not update the state. Any idea why this is not working?
export default function My_editor_popup({visibility_in}) {
const [visibility, setVisibility] = useState(visibility_in);
const popupCloseHandler = () => { setVisibility(false); };
useEffect(() => {
setVisibility(visibility_in);
}, [visibility_in]);
return (
<div>
<MyPopup onClose={popupCloseHandler} show={visibility} title="Editor">
<My_editor text={""}/>
</MyPopup>
</div>
)
}
CodePudding user response:
As I understand, you are using a props, then map try mapping it value to a state using useState and useEffect, then use that state to control the popup visibility. I think you are complicating the problems, because you could simply use the prop to control the visibiliy as shown below
//set visibility is a function which could change value of visibility of parent component
export default function My_editor_popup({visibility, setVisibility}) {
const popupCloseHandler = () => { setVisibility(false); };
return (
<div>
<MyPopup onClose={popupCloseHandler} show={visibility} title="Editor">
<My_editor text={""}/>
</MyPopup>
</div>
)
}
CodePudding user response:
You don't need a useState in this case, you can just use the prop directly. You will need to provide a function to handle the onClose.
export default function My_editor_popup( { visibility_in, closeHandler} ) {
return (
<div>
<MyPopup
onClose={closeHandler}
show={visibility_in}
title="Editor">
<My_editor text={""}/>
</MyPopup>
</div>
)
}