Switching on and off a class in Next.js

I'm a beginner with Next.js and React framework. My question is regarding toggling a class. Here's my attempt in plain JS:

function toggleNav() {
    var element = document.getElementById("nav");
    element.classList.toggle("hidden");
    element.classList.toggle("flex")
    element.classList.toggle("bg-slate-900")

    var toggler = document.getElementById("toggleNav");
    toggler.classList.toggle("false");
    toggler.classList.toggle("rotate-180");
}

I'm using Next.js in combination with TailwindCSS.

Answer №1

If you're looking to expand your skills, diving into React is a great choice.

When working with React, direct element targeting can be tricky. One solution is to utilize the useRef() hook in the following manner:

const App = () => {
  const myRef = useRef()
   
  useEffect(()=>{
    myRef.current.classList.toggle() // and more..
  })
  
  return(
    <div> 
      <h1 ref={ref}>element you want toggle</h1>
    </div>
  )
}

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

What is the best way to implement a dropdown in MUI and React that displays functional components as items?

Here is a list of dummy components: const OwnerList = () => { return ( <Box sx={{ display: 'flex', }} className="owner-container" > <Avatar src='https://hips.hearstapps.com/hmg- ...

What is the best way to utilize regex to replace two elements simultaneously?

I am facing a challenge with manipulating a string of characters by adding span tags to highlight specific words and change their color. While I have successfully implemented the changes for one pattern using regex, I'm struggling to do the same for a ...

Limit the usage of Lightning Web Component instances to only one per user

Is there a way to restrict users in Salesforce to using only one instance of a Lightning Web Component? I am new to Salesforce Lightning Web Components and looking for a solution to limit the number of instances a user can create through either permission ...

Tips for detecting the creation of an iframe before executing any javascript code

Before executing some JavaScript, I am trying to wait for an iframe to be created. I have attempted several methods, but none seem to effectively wait for the iframe. The console error that keeps appearing is Uncaught (in promise) TypeError: Cannot read pr ...

Leveraging JavaScript variables within a jQuery selector

My <form> includes the following input... Term ID: <input type="text" name="data_array[0][term_id]" size="5" value="' . $highest_term_id . '"> with the $highest_term_id being set by PHP. I am attempting to increment the "data_array ...

Exploring the capabilities of Typescript arrays by implementing a forEach loop in conjunction with the

I possess an array: set Array ( [0] => Array ( [name0] => J [name1] => L [name2] => C ) [1] => Array ( [data0] => 3,1,3 [data1] => 5,3 ...

The error code ECONNREFUSED was encountered while trying to access an external API within the Next-Auth

I'm currently troubleshooting an issue involving Next.js (port 3000) and Next-Auth. My setup includes an external local API (port 3001) created using Nest.js, from which I am consuming the auth/login endpoint. Important: The code is located in the ap ...

Utilize ng-repeat to iterate over two arrays

Two arrays are at my disposal here. The first array contains option content, while the second array consists of option tags (i.e., A, B, C, D). How can I structure the layout for the 'input type="radio"' using ng-repeat? To start off, I am attem ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

Endless cycle plaguing Grunt tasks

Currently in the process of setting up a foundation Gruntfile.js for some upcoming projects. Recently started working on a new computer, so I had to rebuild everything from scratch. Used Homebrew to install Node and NPM, followed by installing Grunt global ...

Using jQuery Ajax to send data and retrieve responses in the Codeigniter framework

I am struggling with passing values in CodeIgniter and I need some guidance. Could you provide an example code snippet using CodeIgniter to send a value from a view to a controller using Ajax and jQuery, and then display the result on the same page? In my ...

selecting the ajax url for the datatable

I need to select the datatable ajax URL based on whether it contains data1, data2, or data3. Below is my code snippet: $(document).ready(function() { var $table = $('#datatable1'); $table.DataTable({ "columnDefs": [ ...

Trying to assign a value to a property that is not defined

I'm attempting to initiate the loading and exhibition of a .stl file through three.js by implementing the following code: var stlLoader = new THREE.STLLoader(); stlLoader.load('assets/Cap.stl', function (object){ object.position.y = - 1 ...

What is the best way to ensure that JavaScript code is executed in a specific sequence?

Even though I understand that Javascript is not the same as C# or PHP, I keep encountering an issue with Javascript - specifically with how I use it. Here's the scenario: function updateStatuses(){ showLoader() //displays 'loader.gif' on ...

Ways to clear TextField status

My question is about a Textfield. In the case where the state is null but the text field value is showing in the Textfield. <TextField style={{ width: '65%'}} id="standard-search" ...

Switching from Vue's Options API to Composition API is like transforming your code from

My goal is to transition the code below from using the options API to the composition API in Vue while utilizing Typescript. data() { return { items: [ 'Car', 'Truck', 'Bike', 'Ca ...

Determine the percentage of clicks on an HTML5 canvas radial progress bar

Recently, I designed a circular progress bar displaying a specific percentage. However, I am facing a challenge in determining how to calculate the percentage when a user clicks on either the black or green part of the circle. Could you provide insight on ...

Configuring Next-auth CredentialProvider and setting up redirection

I'm feeling a bit lost when it comes to understanding how the credentials provider and redirects work. The documentation mentions that the credentials provider doesn't support a callback and is specifically for OAuth providers, which I understand ...

Animation issue in Material UI autocomplete label feature

Hello, I am currently delving into the world of React and Material UI. I have been working on implementing the Material UI auto complete feature with chip functionality. You can see my progress here: https://codesandbox.io/s/runh6. Everything seems to be w ...

"Delve into the art of utilizing negative space between elements with

Looking to implement hover detection between rows in a grid container, rather than on individual items. The number of items in the container and per row may vary. It's important to note that the item count in the container and rows is dynamic. The c ...