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

Having trouble running Next.js on iOS? An error occurred while trying to execute the 'insertBefore' function on the Node, resulting in a NotFoundError with the message insertBefore([native code]). It seems like the object you are

After extensive searching, I finally found a solution to an error that was plaguing our iOS Mobile users and a few Android users. This issue was causing severe 500 Application errors on our Nextjs app for our users. Has anyone else encountered a similar pr ...

Is there a way to maintain the checked status of the checkboxes after a page refresh?

Is there a way to keep the checkboxes checked even after the page is refreshed in this code snippet? Any code sample or explanation on how to achieve this would be highly appreciated. The complete project code can be found here: https://github.com/Orelso/P ...

Why are Chakra UI components not responsive to small screen sizes?

Exploring the world of Chakra UI with my brand new NextJs project built using typescript has been quite interesting. I decided to play around with custom styles for the Default Button component, but encountered some issues with applying small size styles a ...

Vue alert: Issue encountered in data() - "TypeError: Unable to convert undefined or null to object"

Can anyone help me figure out how to remove this warning? I suspect it's because I'm trying to manipulate an undefined object. Any assistance would be greatly appreciated! Thank you! Here is the code snippet: <v-card class="ma-3 pa-3" v-for=" ...

Styling text using CSS depending on the displayed text

Utilizing Awesome Tables (AT), I am extracting data from a Google Sheets document to display on a website. The HTML template in the sheets is used for formatting the data, specifically focusing on the table output with inline CSS styling. Since the templat ...

Guide to making a button in jQuery that triggers a function with arguments

I've been working on creating a button in jQuery with an onClick event that calls a function and passes some parameters. Here's what I have tried so far: let userArray = []; userArray['recipient_name'] = recipient_name.value; userArray[ ...

Guide on adjusting the darkness of a MaterialUI Avatar component image and adding text to it

I'm currently working with the Avatar component from Material UI along with Tailwind CSS. I found that by simply adding the image URL to the src, it displays the avatar successfully. <Avatar alt="Cindy Baker" src="https://mui.com/sta ...

Update the Vue method

Is there a way to optimize the following method or provide any suggestions on what can be improved? I am trying to create a function that converts author names from uppercase to only the first letter capitalized, while excluding certain words ('de&apo ...

Show a dynamic modal with a widget displayed inside

I am facing an issue with my Angular.js website that is filled with a multitude of widgets. Each widget consists of a template.html file paired with a controller.js file to form an angular module. These widgets are utilized on a dashboard where users have ...

If the option of "none" is chosen, I would like to deactivate all checkbox selections

Struggling with disabling all checkboxes in a PHP form when the NONE option is selected. <h5>HEALTH OF STUDENT</h5> <p>Any physical, emotional, or other difficulties to be aware of?</p> <table> <td>Hearing ...

Concealing a button once the collapse feature is toggled in Bootstrap

The following code snippet from the bootstrap website demonstrates how to use collapse functionality: <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Link with href & ...

Having issues with Next.js server-side rendering when integrating API functionality

"Not building properly" means that the project is not fully completing the build process. I've developed a simple blog project with dynamic SSR that pulls data from the Notion-API to generate static blog pages. Everything functions correctly ...

Express is unable to locate the specified property

Here is my controller code snippet: exports.showit = function(req, res){ res.render('showpost', { title: req.post.title, post: req.post }) } In my post model, I have included title and name objects: title: {type : String, default : &apos ...

Print directly without the need for a preview or dialog box

Is there a way to easily print content with just one click, without having to go through the preview or print dialog box? Here is a snippet of my code: <head> <style type="text/css"> #printable { display: none; } @media print { #non-pr ...

Obtain precise JSON information using Node.js

Having limited experience with Angular JS and Node JS, I find myself in need of assistance. On the server side, I have multiple JSON files containing language translations. Based on a client's request for a specific language, such as French, I must re ...

Encountering compilation issues with Jest in Vue project, yet the tests are successfully passing

I'm currently facing an issue with my module building while using jest with vue.js for testing. The tests are running successfully, but the module building is failing unexpectedly. I have provided my code snippet below and would greatly appreciate any ...

The TextField is currently unable to be edited because of an Uncaught TypeError stating it is not iterable

Currently, I am fetching data from an API and updating TextFields with it for display. My goal is to allow users to edit the data shown in these TextFields, but I keep encountering a Uncaught TypeError: prev.fields is not iterable error whenever I attempt ...

Some pages are compatible with JS while others are not... Although, the file can be found in the page source

I have limited knowledge in javascript, so I often find myself copy-pasting code. Currently, I am working on a website that includes a navigation sidebar. I have implemented a script to toggle a class that sets the display property to none. $(document).rea ...

The backspace key is unresponsive following the use of a jQuery class

Using a specific class for an input field: Here is the code for the input field: <?php echo $this->Form->input('duration', array('class'=>'input-large text-right number-field','value'=>'0&apo ...

Using PM2 to Manage Your PHP Scripts in Cluster Mode

Currently, I have been effectively managing single instances of PHP daemons with PM2, and so far everything is running smoothly! When it comes to managing Node.js/IO.js apps with PM2, I can easily launch them in cluster mode without any issues. However, t ...