Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React collapse pro-sidebar on click

I am a newbie to React. I have a react-pro-sidebar that I want closed/opened on click:

export default function MaterialLayout(props) {
 const { children } = props;
 const classes = useStyle();
 function CollapseSide() {
   document.getElementById('pro1').collapsed=!document.getElementById('pro1').collapsed;
 }
 
 return (
   <ThemeProvider theme={theme}>
     <CssBaseline /> <Header />
     <ProSidebar id='pro1' onClick={CollapseSide} collapsed={false}>
....
....

What am I doing wrong

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With document.getElementById('pro1').collapsed you’re setting the property on the actual rendered DOM Node and not the React Node.

You can instead try the following

export default function MaterialLayout(props) {
 const { children } = props;
 const classes = useStyle();

 const [ sideCollapsed, setSideCollapsed ] = useState(false);
 const toggleSideCollapsed = useCallback(() => {
   console.log('toggle')
   setSideCollapsed(collapsed => !collapsed)
 }, [ setSideCollapsed ]) // could leave this empty
 
 return (
   <ThemeProvider theme={theme}>
     <CssBaseline />
     <Header />
     <ProSidebar onClick={toggleSideCollapsed} collapsed={sideCollapsed}>
....
....

However I’m not sure whether or not ProSidebar takes an onClick property. You can verify that using the console.log statement and checking your console.

For more explanation you can look into the React docs on useState and useCallback or just ask in the comments 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading