Home > Software design >  i am not able to update modal state based on received props value from other component in reactjs
i am not able to update modal state based on received props value from other component in reactjs

Time:02-13

i am not able to update modal state based on received props value from other component in reactjs. i have tried all things but not working. please suggest on it it will be appreciable.

const ModalExample = ({ elem }) => {

const [modal, setModal] = useState(elem);
useEffect(() => {
    console.log('elem', elem);
})

const toggle = () => {
    setModal(false);
}


return (
    <div>
        <Modal isOpen={modal} toggle={toggle}>
            <ModalHeader toggle={toggle}>Modal title</ModalHeader>
            <ModalBody>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </ModalBody>
            <ModalFooter>
                <Button color="primary" onClick={toggle}>Do Something</Button>{' '}
                <Button color="secondary" onClick={toggle}>Cancel</Button>
            </ModalFooter>
        </Modal>
    </div>
);

}

CodePudding user response:

Instead of passing elem prop directly inside useState

do something like this.

const [modal, setModal] = useState(false)

useEffect(() => {
  setModal(Boolean(elem)) // I suppose it is not boolean so make it boolean
},[elem])
  • Related