Turning a JavaScript and GSAP button into a ReactJS component

HTML

<div class="container">
    <div class="toggle">
        <div class="menu-btn">
            <span class="one"></span>
            <span class="two"></span>
        </div>
    </div>
</div>

CSS

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    display: grid;
    place-items: center;
    height: 100vh;
}

div {
    position: relative;
    z-index: a;
}

.toggle {
    position: relative;
}

.menu-btn {
    position: fixed;
    width: 40px;
    height: 12px;
    cursor: pointer;
    z-index: 10;
}

span {
    position: absolute;
    width: 100%;
    height: 2px;
    background-color: #000;
}

.two {
    margin-top: 12px;
}

JAVASCRIPT

$(document).ready(function() {
    
    var t1 = new TimelineMax({paused: true});
    
    t1.to('.one', 0.8, {
        y: 6,
        rotation: 45,
        ease: Expo.easeInOut
    });
    
    t1.to('.two', 0.8, {
        y: -6,
        rotation: -45,
        ease: Expo.easeInOut,
        delay: -0.8
    });
    
    t1.reverse();
    $(document).on('click', '.menu-btn', function() {
        t1.reversed(!t1.reversed());
    });
});

I NEED HELP WITH IMPLEMENTING THIS IN REACT:

PLEASE MAKE SURE TO INCLUDE GSAP :

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/gsap.min.js"</script>

HERE IS THE LINK TO THE CODEPEN EXAMPLE : https://codepen.io/doesnotexist/pen/XWXKMmJ

When I tried to replicate the behavior in React, I encountered numerous errors which I couldn't resolve.

Answer №1

To start off, it's worth mentioning that using GSAP for this task may not be necessary. Simple CSS animations were utilized to rotate the two bars in this example.

For a demonstration, check out the live example here

React Code Snippet:

import React, {useState} from "react";

function MenuButton(props) {
  const [toggle, setToggle] = useState(false);
  return (
    <div
      class={`menu-btn ${toggle ? "on" : "off"}`}
      onMouseOver={() => setToggle(true)}
      onMouseOut={() => setToggle(false)}
    >
      <span class="one"></span>
      <span class="two"></span>
    </div>
  );
}

To integrate this button into your React component, use the following code:

<MenuButton />

CSS Styles:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: grid;
  place-items: center;
  height: 100vh;
}

.menu-btn {
  position: relative;
  width: 40px;
  height: 12px;
  cursor: pointer;
  z-index: 10;
}

.menu-btn span {
  position: absolute;
  width: 100%;
  height: 2px;
  background-color: #000;
  transition: transform 0.2s;
}

.menu-btn.off span:first-child {
  transform: translateY(-5px) rotate(0deg);
}
.menu-btn.off span:last-child {
  transform: translateY(5px) rotate(0deg);
}

.menu-btn.on span:first-child {
  transform: translateY(0px) rotate(45deg);
}
.menu-btn.on span:last-child {
  transform: translateY(0px) rotate(-45deg);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The incorporation of SVG within a span disrupts the conventional left-to-right arrangement of its child elements

As I was working with some basic HTML, I encountered an issue. <span> <span>Hello</span> <span>World</span> </span> The above code displays: Hello World However, when I tried adding an SVG element like this: <s ...

Using JavaScript with ASP TextBox to enhance functionality

I'm struggling with allowing the client to input values into an asp TextBox to track the amount of hours spent on various activities. I'm having trouble transferring these values into javascript and running the code on button click. Any assistanc ...

Ways to conceal a primary page section upon clicking a different tab

I am currently implementing the w3schools HOW TO - tabs feature on my website to create tabbed navigation. However, I'm running into an issue where clicking on tabs other than 'Home' still displays the 'Home' content along with the ...

What steps should I take to address a situation in which a Protractor test becomes stuck indefinitely?

I've encountered an issue with a test case that was previously running successfully but is now getting stuck indefinitely during execution. This problem occurs each time the test attempts to click on a specific element, causing the test to hang withou ...

I am unable to display my JSON data in Next.js using a fetch request

I'm having trouble understanding the code, and it seems like the API is open to anyone since it's just a simple JSON. However, I keep getting an error: Error Message: Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit th ...

"Typescript Conditional Date/String Return Type: Making Informed Return Dec

Is there a way to apply a function that returns either a string or a Date, depending on the type of the value parameter? I'm currently having to use type assertion in the function call <Date>toggleDateString(stringValue) because I keep getting ...

Switching between different paths in a Next.js 14 application to display a single component

In my project using Next.js 14 and next-intl, I am currently working on setting up a routing system where different URL paths display the same component based on the pathname. The application is multilingual, with each language version having its own uniqu ...

Assign an event listener to a collection of elements

Suppose I have an Array containing elements and another Array consisting of objects in the exact same index order. My goal is to add a click event for each element that will display a specific property of each object. For instance: myDivArray = [ div0, d ...

Getting HTML Table Data with Jsoup Library

Is there a way to utilize Jsoup in order to extract specific data from this particular website in a structured manner for each individual row, such as Network Type, Battery, etc.? import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup ...

Incorporate some flair into the Twitter iframe with a Style tag

I have been attempting to add a style tag into the head of an embedded Twitter timeline in order to customize some of the styling. I wrote the CSS and added it within a style tag. My initial idea was to inject this into the iframe using jQuery, but unfortu ...

Are there any available polyfills for downloading links using data URIs?

My issue involves generating code from the server: <a download="test.csv" href="data:text/plain;charset=utf-8;base64,w4FydsOtenTFsXLFkXTDvGvDtnJmw7p0w7Nnw6lwLg=="> teszt </a> This solution currently works with Chrome, Firefox, and Opera. ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

Retrieval is effective in specific situations but ineffective in others

I have encountered an issue with fetching data only when using the async behavior. I am currently in the process of re-building a property booking website that was originally developed using Laravel and a self-built API. The new version is being created wi ...

The function being called within useEffect is rendering too quickly, causing it to break. However, it functions correctly after

When using React-id-swiper to load images for products, I encountered an issue with setting the useState 'loading' state to false after all images have been successfully loaded. In this case, there are 5 products. To achieve this, I implemented ...

What could be the reason that my Javascript function is not displaying in the HTML document?

I'm currently working on developing an HTML page that displays random quotes by Mark Twain. The function and array of quotes are set up in a separate Javascript file which is linked to the main HTML document. However, I am facing an issue where the ou ...

Is it possible for JavaScript to detect elements or scripts within a hidden element using display="none"?

Is it possible for scripts to locate elements that have been hidden in the DOM by setting their attribute to display="none"? ...

I am encountering an error when trying to read the property 'getState' of undefined in Next.js with Redux and PersistGate

An error occurred while migrating from Create React App to Next. I am unable to use Redux and have tried multiple solutions without success. https://i.stack.imgur.com/gfOaE.png _app.js import "../styles/globals.css"; import App from "next/app"; import { ...

Using jQuery's "When Done" function on a dynamically generated function call

Here is the JavaScript code snippet: In the file site-code.js .... var ajaxContentFunc = $(origin).data("modal-content-handler"); $.when(window[ajaxContentFunc]()).done(function (resp) { kModal.showContent(resp); }); In another file, there is an & ...

Searching for items in a JSON object using binary search

My JSON object contains data organized like this: "time1": { "item1": "val1", "item2": "val2" }, "time2": { "item1": "val3", "item2": "val4" } ... The time* values represent dates in milliseconds and are sorted in sequence. Now, I need t ...

When trying to initiate `npm start` on a Windows system, nothing seems to happen

Working on developing an app using create-react-app with the command: create-react-app my-app After creating the app, running npm start results in no output and the app fails to start. Here is what appears: <a href="/cdn-cgi/l/email-protection" class=" ...