Reputation: 349
I am doing my react project to create side navigation bar.
So I have this button on clicking that button side side navigation bar should open.
<button className="openbtn" onClick={(e) => openNav(e)}>☰ Open Sidebar</button>
This is my openNav function
function openNav() {
console.log("open nav")
document.getElementsByClassName("sidenav").style.width = "250px";
document.getElementsByClassName("test").style.marginLeft = "250px";
}
When I am doing that I am getting this error
Uncaught TypeError: Cannot set property 'width' of undefined
my sidenav styles looks like
.sidenav {
margin-top: 50px;
height:100%;
width: 0px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: white;
overflow-x: hidden;
padding-top: 20px;
font-size: 15px;
}
In css file both sidenav and test has width property.
So how to solve this?
This works in normal html/css/javascript how to do it in react ?
Upvotes: 1
Views: 1180
Reputation: 15213
Using getElementsByClassName()
, you are referring to the collection. Specify the first number in the array as [0]. Try this code:
function openNav() {
console.log("open nav")
document.getElementsByClassName("sidenav")[0].style.width = "250px";
document.getElementsByClassName("test")[0].style.marginLeft = "250px";
}
Upvotes: 1
Reputation: 1156
document.getElementsByClassNamereturn more than one elements. So, you can't just write
.style.width`. Instead you need to run the loop.
const navEl = document.getElementsByClassName("sidenav")
for (var i = 0; i < navEl.length; i++) {
navEl[i].style.width= "250px";
}
Or you're just interested in one element, go with
document.getElementsByClassName("sidenav")[0].style.width= "250px"
Finally, you've typo in question as getElementsByClassNamed("test")
. An extra d
after ClassName
.
Upvotes: 1
Reputation: 11
document.getElementsByClassName("sidenav")
is HTMLCollection
. You need to iterate for each element and assign style for them.
let sideNav = document.getElementsByClassName("sidenav")
for(let i = 0; i < sideNav.length; i++)
sideNav[i].style.width = "250px"
Upvotes: 1