1

What's the proper way to create a class toggle function for a slide in menu in Next.js?

I've created a menu, which has togglable slide-in functionality. There's a button which toggles a class "toggled" and then the menu slides in from the side. I'm not sure if such an approach in itself is wrong when using React/Next.js, in which case I'd appreciate alternatives.

So normally I would inline my toggle-script somewhere in the footer, to get optimal speed. It's a very small script, so it doesn't need to be included in a separate file. I just have no idea where to put this script when using Next.js.

I've read that you can use next/head and put the code in a separate file and include the file normally there, but that doesn't sound very optimal to me. This creates a separate request and makes the whole thing slower than it needs to be. And, if it needs to be done this way, how would you preload/push it if you wanted to do that?

1
  • You should be integrating the logic of the script into the relevant component within your react app rather than including it as a separate script. Commented Apr 26, 2021 at 17:23

1 Answer 1

1

Create a React component - the logic will live there. There is no need to have a separate script file like you would normally have

import React, { useState } from 'react';

const Menu = () => {
  const [toggled, setToggled] = useState(false);

  const class_name = toggled ? 'menu--toggled' : 'menu';

  return (
    <div className={class_name} onClick={setToggled(!toggled)}>
      <div>Menu Item 1</div>
      <div>Menu Item 2</div>
    </div>
  );
};

Hope this sets you on the right track

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer! I've looked into this, but I'm not getting it to work out of the box. What is the checked variable in the example? Could you explain how this is supposed to work?
@dansan sorry that should have been toggled instead of checked. I have updated the answer. This is just a very rough example of a React menu component that can slide in and out
Alright, I figured it would be that, but I still didn't manage to get it working. class_name shows up as "--toggled" no matter what I do. I've never seen && used in a declaration like this.
sorry - another dumb mistake.. I've updated again
Works great now, thanks! This definitely helps a lot, but I've still got a lot of questions regarding this. For example, let's say I want to toggle a class on an element outside of the component? (For example on the body tag)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.