Search code examples
reactjsreact-hooksmaterial-uireact-context

React - Passing State Back to Parent - UseContext


I have a MetaTable Component that has LeftSidePanel wrapped with the UseContext. I want to open the panel when button is click on the MetaTable (passing some data to show detail of a particular record). My code works to open the Panel but when I click outside it doesn't close.I think I would need to set the State back on the parent. Tried a few things but failed. Any guidance please?

MetaTable Component

    export const DrawerDataContext = createContext();
    export const DrawerContext = createContext();
    
    const [isDrawerOpen, setDrawerOpen] = useState();
    const [bookId, setBookId] = useState({});
    
    const toggleSidePanel = (row) => {
        setBookId(row)
        setDrawerOpen(true);
    
      }
    
    ... <TableCell className={classes.tableCell}>
                          <Stack spacing={0}>
                            <Typography variant="body2" my={0}>
                              {row}
                            </Typography>
                            <Typography variant="body2" my={0}>
                              {row}
                            </Typography>
                          </Stack>
                          <Stack spacing={2}>
                            <button onClick={() => { toggleSidePanel(row); }} >toggle drawer</button>
                          </Stack>
                        </TableCell>...
    
    
    <DrawerDataContext.Provider value={bookId}>
            <DrawerContext.Provider value={isDrawerOpen} >
              <LeftSidePanel />
            </DrawerContext.Provider>
          </DrawerDataContext.Provider>

LeftSidePanel Component

const book= useContext(DrawerDataContext);
const open = useContext(DrawerContext);

return (
        <>

            <Drawer open={open} onClose={() => !open} anchor='left'>

                <List style={{ width: 500 }}>

                </List>
            </Drawer>
        </>
    );

Solution

  • In addition to the value of your state, you can also share a function with your context to change its value:

    <DrawerContext.Provider value={{
      isOpen: isDrawerOpen,
      close: () => setDrawerOpen(false)
    }}>
    

    And in your component:

    const book = useContext(DrawerDataContext);
    const { isOpen, close } = useContext(DrawerContext);
    
    return (
      <>
        <Drawer open={isOpen} onClose={close} anchor='left'>
          <List style={{ width: 500 }}>
    
          </List>
        </Drawer>
      </>
    );