Switch the visibility of a div tag using Next.js

Script

export default function Navigation(){
  let displayMenu = false;
  function toggleMenu()
  {
    displayMenu = !displayMenu;
  }
  return (
    <>
      <button onClick={toggleMenu}>Toggle Navigation</button>
      {/*This code should toggle on and off when the button is pressed*/}
      <div style={{
        display: displayMenu?"block":"none"
      }}>
        This should toggle the menu display
      </div>
    </>
  );
}

Objective

The visibility of the div element should toggle (For instance, showing the div tag after one click on the button, hiding it after another click, and so forth).


Actual Outcome

Though the variable displayMenu changes, the div element does not react to these modifications and remains hidden.

NOTE: This script is being used in a next.js environment.

Answer №1

To ensure that React re-renders the component when showMe changes, it is essential to declare showMe as a state variable. Check out this resource for more information: https://reactjs.org/docs/hooks-state.html

The modified code snippet below demonstrates how useState is utilized instead of directly assigning to showMe.

export default function Header(){
  const [showMe, setShowMe] = useState(false);
  function toggle(){
    setShowMe(!showMe);
  }
  return (
    <>
      <button onClick={toggle}>Toggle Subjects</button>
      {/*The bottom code should toggle on and off when the button is pressed*/}
      <div style={{
        display: showMe?"block":"none"
      }}>
        This should toggle my display
      </div>
    </>
  );
}

The syntax

const [showMe, setShowMe] = useState(false);
involves Array Destructuring. Learn more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

When using useState, an array with two elements is returned. By utilizing array destructuring, we assign the first element to showMe and the second element to setShowMe.

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

Is there a way to programmatically create multiple MUI Select components with their corresponding options?

Through processing existing data, I am dynamically generating multiple MUI "<Select>" elements. However, when interacting with one of the "<Select>" elements, the selected value is being applied to all other "<Select>" elements. For inst ...

Node.js Export Module Error - importance of separating concerns

I have been attempting to implement separation of concerns by using export module. Everything functions properly when used without separating concerns, but as soon as I try to import generateUrlArray() from const db = require('../db'), nothing se ...

Encountered an error with "Unexpected token import" while attempting to run pm2 on my React application deployed on a Digital

As I attempt to deploy my application on DigitalOcean and run it with pm2, I encounter the following error: /home/bcavenagh/social/src/index.js:1 (function (exports, require, module, __filename, __dirname) { import React from 'react'; ...

Incorporate an external object not native to the Angular framework within a factory

We're in the midst of a debate and I'm hoping you can help us reach an agreement. Imagine I have a basic factory set up like this: angular.module('myModule', []) .factory('Fact', function() { var Fact = function() { ...

Error: VueJS mixins do not include the property definition

I've been trying to incorporate Mixins into my Vue.js code, but I've run into a few issues :/ Here's the current code for two test modules : ErrorBaseMixin.vue <script> import ErrorAlert from './ErrorAlert'; expor ...

Vue.js numerical input module

My approach involves utilizing Numeral.js: Vue.filter('formatNumber', function (value) { return numeral(value).format('0,0.[000]') }) Vue.component('input-number', { templa ...

The slot "update" is required in the amp-live-list component

This appears to be a duplicate query as I have extensively searched on Google but could not find any relevant thread. The code is located under pages/amp/amp/ export const config = {amp: true}; const posts = [ { body: "Vivamus viverra augue lib ...

Is it possible to eliminate a style that was applied using the .css() method?

Currently, I am using jQuery to modify the CSS and would like to know how to remove the styling that is being applied based on the input value provided: If the color is not '000000', then change the background-color of the body element to the sp ...

The error message in Nextjs is indicating that the Swiper scss package path could not be

Encountered an issue while integrating swiper in Next.js. "next": "^11.1.2", "swiper": "^7.0.5" Despite using the specified versions, unable to access swiper.scss. Seeking guidance on resolving this problem. Error ...

Position the Material-UI AppBar and Tab on the far right of the screen

I am trying to achieve a specific layout where the Links for "Homepage Login Settings and etc.." are placed at the right edge of the AppBar, while keeping the "Website" aligned to the left edge of the screen. Here is what I have: Can someone help me figur ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Issue: The content of the text does not align with the HTML generated by the server

I'm struggling with an algorithm in next.js and encountering hydration errors. Here is the code I am using: import numbers from "../../functions/numberGenerators.js" export default function test() { ...

Is there a way for me to choose a single file while executing the migrate-mongo up command?

Hey there! I'm looking to execute the command migrate-mongo up in just one specific file. Currently, when I run the command migrate-mongo up, it processes all pending migration files. Is there a way to target only one file for execution? For example: ...

Displaying child properties in a functional ReactJS component

React version 0.14 introduces the concept of pure functional components, ensuring that the same input always results in the same output. Props are passed as function arguments. // Using ES6 arrow functions with implicit return: const PureComponent = ({url ...

Enhance User Experience with Dynamic Scroll Page Transition

Hey everyone! I've been working on revamping a website and stumbled upon this fascinating page transition that I would love to replicate. However, I haven't been able to find a JQuery library that can achieve this effect. Does anyone have any i ...

There has been a mistake: The module '.... ode_modules erser-webpack-plugindistindex.js' cannot be found. Please ensure that the package.json file contains a correct "main" entry

After setting up Vue.js and executing npm run serve, I encountered the following error: PS C:\Amit\Demo\VUEDemo\myvue> npm run serve > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f5e1eeedfdd8a8b6 ...

Divide a SINGLE BACKGROUND IMAGE in HTML into two separate links of equal size, one at the top and

As a beginner in HTML, I am trying to find a way to divide a background image into two equal sections without using image mapping. I attempted to split the links by setting the style to 0% and 50% to designate the top and bottom halves, but unfortunately, ...

When React first fetches data and users move to chat with each other, the state value does not update

Recently, I started learning about React and Node.js as I dive into building a chat application. When a user is clicked for one-on-one chat, I retrieve records from the database using backend Node.js and also incorporate socket.io. In my Chat.js file: imp ...

Passing Parameters to Razor Pages Controller

Within my controller, there exists a function as follows: public ActionResult AddSubSub(int? idOfSubsub) { return RedirectToAction("Index", new { searchword = "" }); } I am able to invoke this function without providing any parameter. I attempted the ...

I am experiencing problems with invalidating queries following a mutation

Body: In my React project, I'm handling money transfer operations using React Query for data fetching and state management. One issue I'm facing is that the query does not invalidate after a successful transaction, except if I manually invalidat ...