Home > Mobile >  Can you change the state of two components with one button
Can you change the state of two components with one button

Time:08-15

I'm trying to create an onboarding or three modal series with React MUI. Basically after the button within the modal is clicked it will go to the next modal. I've looked at packages but they are complex for my use case. What's the best way to accomplish this? I can try updating the current state of modal to close and updating another modal state to open at the same time, is that possible?

    const [open, setOpen] = React.useState(false);
        
    const [openTwo, setOpenTwo] = React.useState(false);
        
    const handleOpen = () => setOpen(true);
    const handleClose = () => setOpen(false).setOpenTwo(true);
    
    <Modal
    open={openTwo}
onClose={handleClose}>
{Modal content here
</Modal>

CodePudding user response:

Youre implicitly returning setOpen(false) with your arrow function in handleClose(), you can read more about arrow functions here, but the important bit is

if the body requires additional lines of processing, you'll need to re-introduce braces PLUS the "return" (arrow functions do not magically guess what or when you want to "return"):

since you are calling setOpen, and setOpenTwo you don't need to return anything though

const handleClose = () => {
    setOpen(false)
    setOpenTwo(true)
}
  • Related