I am new to react and i need some help.
I am trying to implement some hamburger menu icon that someone put on codepen:
https://codepen.io/rss/pen/OJxZrR
The problem is that i can't get animation to work.
import "../../index.css";
const [style, setStyle] = useState("nav-container");
const changeStyle = () => {
setStyle("pushed")};
I tried something like this and I added button onClick for changing state but it doesn't work
<button
onClick={() => {
changeStyle();
}}
>
<div id="nav-container">
<div className="toggle-icon">
<span className="bar"></span>
<span className="bar"></span>
<span className="bar"></span>
</div>
</div>
</button>
You can use the state as a toggle and set the class pushed if the state is true
import "./styles.css";
import { useState } from "react";
export default function App() {
const [pushed, setPushed] = useState(false);
const changeStyle = () => {
setPushed(!pushed);
};
return (
<button
onClick={() => {
changeStyle();
}}
>
<div id="nav-container">
<div className={`toggle-icon ${pushed ? "pushed" : ""}`}>
<span className="bar"></span>
<span className="bar"></span>
<span className="bar"></span>
</div>
</div>
</button>
);
}
I think you need to provide dynamic id to the div, as:
<div id={style}>
<div className="toggle-icon">
<span className="bar"></span>
<span className="bar"></span>
<span className="bar"></span>
</div>
</div>
You just need to toggle pushed
class on nav-container
div
Change your onClick handler to this
const changeStyle = () => {
const navContainer = document.getElementById("nav-container");
navContainer.classList.toggle("pushed");
};
Some precautions -
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.