I am trying to build a toggle sidebar. when I click on the button the class list of .m-toggle should be updated. But react gives me an error
"TypeError: Cannot read property 'classList' of null"
Here is my code:
import React, { useState, useEffect } from 'react'
// import Sidebar from '../Components/Sidebar'
import AppleIcon from '@material-ui/icons/Apple'
import DashboardIcon from '@material-ui/icons/Dashboard'
import PeopleIcon from '@material-ui/icons/People'
import NotificationsIcon from '@material-ui/icons/Notifications'
import SettingsIcon from '@material-ui/icons/Settings'
import HelpIcon from '@material-ui/icons/Help'
import img from '../Assets/img/keval.jpg'
function toggleMenu() {
let toggle = document.querySelector('.m-toggle')
toggle.classList.toggle('m-active')
}
const Main = () => {
return (
<>
<div className="m-body">
<div className="m-container">
{/* -------Sidebar Start------- */}
<div className="m-navigation">
<ul style={{ padding: '0' }}>
<li>
<a href="#">
<span className="m-icon">
<AppleIcon className="muicon" />
</span>
<span className="m-title">
<h2>Brand Name</h2>
</span>
</a>
<hr style={{ color: 'white' }} />
</li>
<li>
<a href="#">
<span className="m-icon">
<DashboardIcon className="muicon" />
</span>
<span className="m-title">Dashboard</span>
</a>
</li>
<li>
<a href="#">
<span className="m-icon">
<PeopleIcon className="muicon" />
</span>
<span className="m-title">Employees</span>
</a>
</li>
<li>
<a href="#">
<span className="m-icon">
<NotificationsIcon className="muicon" />
</span>
<span className="m-title">Notification</span>
</a>
</li>
<li>
<a href="#">
<span className="m-icon">
<HelpIcon className="muicon" />
</span>
<span className="m-title">Help</span>
</a>
</li>
<li>
<a href="#">
<span className="m-icon">
<SettingsIcon className="muicon" />
</span>
<span className="m-title">Setting</span>
</a>
</li>
</ul>
</div>
{/* --------Side BAr End--------- */}
<div className="m-main">
<div className="m-topbar">
<div className="m-toggle" onClick={toggleMenu()}>
f
</div>
<div className="m-search">
<label>
<input type="text" placeholder="Search here" />
</label>
</div>
<div className="user">
<img src={img} alt="no img" />
</div>
</div>
</div>
</div>
</div>
</>
)
}
export default Main
You can see the code where onclick class list should be updated but it is not updating.
display: nonefor.m-toggleor a parent element. If you want to get the element viaquerySelectoryou need to usevisibility: hiddenonClick={toggleMenu()}which calls the function immediately even before mount. You should useonClick={toggleMenu}thisalready refers to the element