Using JavaScript code in ReactJS does not produce the desired results

Just starting out with react and could use a little guidance.

I came across this interesting hamburger menu icon on codepen:

https://codepen.io/rss/pen/OJxZrR

The challenge I'm facing is getting the animation to function properly.

import "../../index.css";

const [style, setStyle] = useState("nav-container");


const changeStyle = () => {
setStyle("pushed")};

I attempted something similar to this and included a button onClick event to toggle state, but it's not working as expected.

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

Answer №1

To create a toggle effect, utilize the state and apply the class "pushed" when the state is true

import "./styles.css";
import { useState } from "react";

export default function ToggleButton() {
  const [isPushed, setIsPushed] = useState(false);

  const toggleStyle = () => {
    setIsPushed(!isPushed);
  };
  return (
    <button
      onClick={() => {
        toggleStyle();
      }}
    >
      <div id="nav-container">
        <div className={`toggle-icon ${isPushed ? "pushed" : ""}`}>
          <span className="bar"></span>
          <span className="bar"></span>
          <span className="bar"></span>
        </div>
      </div>
    </button>
  );
}

Answer №2

In my opinion, adding a dynamic id to the div is essential for better functionality:

<div id={dynamicId}>
            <div className="toggle-icon">
              <span className="bar"></span>
              <span className="bar"></span>
              <span className="bar"></span>
            </div>
          </div>

Answer №3

To make the desired effect, simply switch the pushed class on the nav-container element.

Modify your onClick function like so:

const updateStyle = () => {
  const navigationContainer = document.getElementById("nav-container");
  navigationContainer.classList.toggle("pushed");
};

Answer №4

Here are a few safety measures to consider:

  • Ensure that your button hovers change the cursor to a pointer. Otherwise, you may encounter a low z-index issue.
  • const modifyStyle = (e) => { e.preventDefault(); togglePushedState(!pushed); };
  • Since there is no content within it, verify its presence.

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

using node.js to save query results as global variables

Help needed! I'm struggling to pass the results of my query statement to a global variable in order to dynamically configure my jsganntimproved chart. Any suggestions on what could be going wrong? In the snippet below, the console.log(taskItem) retur ...

Discover a technique to display every individual "echo" statement from PHP in sequence, rather than waiting for the entire script to finish executing

I have developed a PHP script that takes some time to execute and displays multiple "echo" statements as the progress is being made. The script connects to an FTP server, deletes all contents, and then uploads new files. Everything is functioning correctly ...

What is the best way to adjust the height of a dropdown box in an angular application?

Is there a way to change the height of the scroll view? It seems too long for my liking, any advice? I attempted to adjust it using css but unfortunately, it didn't work out. The scroll view appears excessively lengthy as shown in the image below. h ...

CSS Device Media

I am currently working on my first website and I am striving to develop a responsive layout. Below is the HTML code I have implemented: <link href="css/web_desktop.css" rel="stylesheet" type="text/css" media="screen and (min-width:481px)" /> <l ...

Angular routing and parameters are not functioning as expected

In my code, I have implemented the following controller: app.controller('ObjectBoardCtrl', ['$scope' , '$rootScope' , '$routeParams' , function($scope , $rootScope, $routeParams) { $scope.selectedObjectId = $ ...

JavaScript: Obtaining the month based on the week number and year

Can someone assist me in determining the month based on a given week number and year? For example: Week - 48 Year - 2023 Desired Output - 11 ...

What are some ways I can incorporate async and await within a React render function?

I'm currently working on a react-native application and I am looking to implement multi-language support. To make the process easier to manage, I have created a languageHelper. Here is the code for languageHelper.js: import AsyncStorage from '@r ...

Constantly loading image with Meteor HTTP request

Within my Meteor application, I am attempting to dynamically load a random image from an API which returns JSON data structured like this: { "id":2026 "url": "https:// ... " , "large_url":null, "source_id":609, "copyright":"CC0", "site":"unsplash" } ...

Exploring and verifying data within an array in ReactJS

In ReactJS, there is a variable that contains the result of validation as an array: console.log(this.state.check); // [account: false, name: true, email: true] Here's what needs to be done: If all values in the array are true, return true. If one or ...

Customize the input of MuiSwitch in Material-UI v5

I'm facing an issue where I need to utilize the Switch component from MUI v5 on a website that already has third party CSS affecting the positioning of checkboxes and radios. In the previous version, v4, I was able to address this by using an overrid ...

Encountering a login issue with the jsonwebtoken code, specifically getting the error message "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')."

I encountered an error in my console saying, "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')." I am seeking assistance in resolving this issue. Below is the code snippet: import { mAdmin } from &q ...

Building a conditional statement in React based on the URL path: A beginner's guide

I want to incorporate a transparent menu specifically on the homepage. How should I go about this? I've established a constant named isHomePage and now I need to set a URL (the index.tsx) to define this constant. function MyApp({ Component, pageProps ...

Incorporating a way to automatically initiate a GET request following a POST request in React can effortlessly display a new

In my App component, I display a list of items and have a ModalForm where users can add new items. However, after adding a new item, I currently have to reload the page in order to see it in the list. I am looking for a way to automatically trigger a GET ...

Maintain the background color of the form select drop down even after clicking away from the form

I have customized a dropdown menu. <select name="country"> <option value="Andorra">Andorra</option> <option value="Albania">Albania</option> <option value="Armenia">Armenia</option> <opt ...

Using NodeJS to convert a Base64 string into a JPEG image with the help of either NodeJS or

I have successfully stored a JPEG image in my MySQL database using the longblob format. Now, when I retrieve the longblob data, I am only getting a base64 string. How can I convert this base64 string back to a readable JPEG image using MySQL or Node.js? B ...

Issue with MVC page redirection not functioning properly after successful completion of an AJAX request

After successfully retrieving data from an AJAX call, I am trying to redirect to '/Account/Index' in the AJAX success function. However, for some reason, the redirection is not working as expected. Is there any other way to perform a redirection ...

What is the process for including .php and .js files within WordPress?

Seeking guidance from experienced WordPress users! I am a PHP expert trying to integrate .php files into WordPress using the Visual Editor. My aim is to validate HTML forms by utilizing Ajax calls to these scripts. Although proficient in PHP and various ...

What steps should I take to repair my image modal button?

Within my application, I have an image modal placed inside a header tag, along with a label. There is some space between the label and the image modal. However, when the application is run, the page appears in a fixed position, but the label message does n ...

Issue with React Material-UI Select component not displaying the chosen value

Hi there, I'm facing a problem with the MUI select function while trying to choose a country. I can see that when I select a country, its value changes, but nothing appears inside the select box. const [selectedCountry, setSelectedCountry] = useState( ...

What is the best way to rotate a ThreeJS Object3D object around its endpoint?

Can an Object3D object be rotated around its end point? I located the center of my object using const boundingBox = new THREE.Box3().setFromObject(this.object). Would rotating at a specific point involve moving the object to that point, rotating it, and ...