Search code examples
javascriptreactjssidebar

Keep the selected options in the Sidebar when resizing the screen


My site has a sidebar (FiltersSideBar in my code) that contains filters. When the browser is expanded to full screen, the sidebar is in open mode on the left. If the screen width becomes less than 600, the sidebar is hidden and a button (ArrowBackIosNewIcon in my code) appears that can open the sidebar (as if overlaying the home page).

The problem with my code is that when the sidebar changes position (opens/closes), its state is not saved - all sidebar elements return to their original state. Although the applied filters continue to work.

That is, if the user selected any filters in the full-screen mode (for example, checked some categories), they were applied. But after that the browser window shrinks, the filters themselves remain applied, but the sidebar is displayed in the default mode (i.e. the checkboxes are empty again).

I would like to make it so that regardless of the size of the page the sidebar retains its appearance.

FiltersSideBar.jsx

 export default function FiltersSideBar(props) {
    return (
        <CardContent className={props.className}>
            <Table>
                <TableBody>

                    <TableRow>
                        <TableCell>
                            <Filter1 />
                        </TableCell>
                    </TableRow>

                    <TableRow>
                        <TableCell>
                            <Filter2 />
                        </TableCell>
                    </TableRow>
                    
                </TableBody>
            </Table>
        </CardContent>
    );
}

Solution

  • I don't see how you pass the filters to the sidebar.

    But this issue happens because you completely destroy the sidebar to hide which resets its state to default, it would be better to just manipulate the style with display and transition without destroying the sidebar.

    like here. https://codesandbox.io/s/zealous-hodgkin-lf7qwt

    Another solution is to make the filters state in the parent component of the sidebar and pass props to it.