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

The HTML grid is causing an irritating excess space on the right side of my website

After brainstorming an idea, I decided to create this website for testing purposes. However, the grid layout seems to be causing an unwanted margin on the right side of the page that is not associated with any HTML tag, disrupting the zoom functionality. ...

Title: Troubleshooting Nest.js Google OAuth Redirection Problem with CORS Blocking

I am currently encountering an issue with my Nest.js application that utilizes Google OAuth for authentication. The backend of Nest.js is running on port 5000, while the frontend (Next.js) is running on port 3000. I have properly configured the Google Clou ...

The next.js docker error I encountered was related to getServerSideProps, showing a connection error with code "connect ECONNREFUSED 172.25.0.2

I have two separate docker-compose.yaml files. One is for the backend which includes its database, nginx, and node.js, while the other one is for my Next.js frontend application. FRONTEND: services: bsb_front: image: bsb_front container_name: b ...

AWS Amplify deployment has revealed React source code

I recently tested the deployment of an app on AWS amplify and here are the steps I took: Started by creating a sample create-react-app, which I named deploy_test, Afterwards, I pushed the code to a GitHub repository, In the AWS Amplify console, I deployed ...

How to creatively position custom arrows in a React JS Nuka Carousel

Seeking assistance on properly positioning custom arrows within the Nuka Carousel component. After combining the decorators, I found that both of my arrows are appearing side by side. How can I address this issue? My goal is to have one arrow positioned in ...

Is it necessary to make multiple calls following a successful AJAX request?

Here is an AJAX call I am setting up. The first step is to hit the endpoint dofirstthing.do. Once that is successful, the next step is to make another call with "param1" as the query parameter. Now, my question is - how can I make a third call with "param ...

Leverage the power of zustand actions in your axios queries!

In my React application, I have implemented Zustand for creating a store: import { create } from 'zustand'; interface IAuth { username: string; isAuthentificated: boolean; updateAuth: (isAuth: boolean) => void; } export const useAuth = ...

The outline color cannot be removed from vue-carousel

I recently downloaded the Vue Carousel library and here is the version I am using: "vue": "^2.6.11", "vue-carousel": "^0.18.0", When I click on the pagination, a focus effect is added to the element with an outlin ...

Invoke a component and initiate a click event from within the App.vue component

Within my template, there is a click event: <span v-on:click="showGalery()"> This event is linked to the following method: export default { name: 'osaka', data: function () { return { galery: false, } }, methods: { ...

The HTML embed element is utilized to display multimedia content within a webpage, encompassing

Currently, I am working on a static website for my Computer Networks course. Students need to be able to download homework files in PDF format from the website. I have used embed tags to display the files online, but I'm facing an issue where the embe ...

Looking to add the Ajax response data into a dropdown selection?

Looking to add select options dynamically, but unsure how to retrieve response values. I am able to fetch all the values in the response, but I struggle with appending them correctly in the select option. I believe the syntax is incorrect. success: funct ...

Convert an array into individual objects and include key-value pairs from a separate object

I am working with two arrays that have the same length: One is a simple array numbers = [4,5,6] The other is an array of objects objects = [ {type: "x", value: 7}, {type: "y", value: 8}, {type: "z", value: 9} ] My goal is to combine th ...

Navigating routes on React.js and Node.js across both server and client sides

I am currently delving into the intricacies of how routes function with react-router in my React application and Express on my Node.js server. Here is my React-router code : import .. import { Router, Route, IndexRoute, hashHistory, IndexRedirect, Redire ...

What is the mechanism behind the setTimeout function as an asynchronous timer when we specify a specific duration?

Can you identify the coding instructor, possibly Net Ninja or Fireship, who explained that in asynchronous setTimeout, it promises to run after a minimum time of 1 second but may actually take longer (e.g. 1015 milliseconds or 1200 milliseconds)? What ha ...

Retrieving the checkbox's status from the database

I have implemented a basic checkbox that updates its state in the database when clicked or unclicked. Is there a way to retain this state and have it displayed as checked if the page is refreshed? Essentially, I want the checkbox to remember its last state ...

Failure to trigger AJAX error function when database match is not located

UPDATED: Having some issues with my code entry box when a match is not found in the database. Below are the results for both a good and bad match. Check out my code snippet: function checkDiscountCode() { var discount; if ($('#dbReturnString') ...

What is the process for generating a null result cursor upon publication?

Is it possible to return an empty cursor in Meteor? Meteor.publish('example', function(id) { check(id, Match.Maybe(String)) if (!this.userId) return [] }) Although I want the publication to return an empty result when the user is not lo ...

Converting HTML elements into Vue.js Components

In my Vue.js application, I am utilizing a d3.js plugin to generate a intricate visualization. I am interested in implementing a customized vue directive to the components that were incorporated by the d3 plugin. It seems that the $compile feature, which ...

The Next.js application is unable to load the combined CSS from a React Component Toolkit

My React components repository includes individual .css files for each component which are imported into the respective components. These components are then bundled using a rollup configuration and published as an NPM package, with all component CSS being ...

Incorporate socket.io into multiple modules by requiring the same instance throughout

I am feeling a bit lost when it comes to handling modules in Node.js. Here's my situation: I have created a server in one large file, utilizing Socket.io for real-time communication. Now, as my index.js has grown quite big, I want to break down the ...