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
>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 🙂