DEV Community 👩‍💻👨‍💻


Posted on

How i made a easter egg function in next.js

I needed a basic function in NextJS where if you press a key combination a specific number of times the given object or content will be shown/hidden. I'm in no way an expert in NextJS but this is the solution I came up with, which seems to work flawlessly.

The library I used for this was react-use-keypress, this was the only one I found that functioned the way i wanted it to. Down below is the code.

import useKeypress from 'react-use-keypress';
import { useState } from 'react';

export function ShowSomething() {
    const [shown, setShown] = useState(false);
    const [count, setCount] = useState(0);
    // Use keypress library
    useKeypress('e', (e) => {
        if(count < 4) return;
        if(shown) setShown(false);
        if(!shown) setShown(true);
        if(count >= 5) setCount(0);
    // Return to dom
    return <div className={`${shown ? 'visible' : 'hidden'} other-classes`}>Something to show</div>
Enter fullscreen mode Exit fullscreen mode

The shown state is the one deciding wether or not the element gets shown or not & the counter is to see how many times the key was pressed. Then if the count is lower than 4 it'll not show the given content, however if it's past the 4 check it'll return shown depending wether the state is shown or not. Lastly the last check in the useKeypress is to see if the value is above or equal to 5 that will basically reset the counter.

Hope you enjoy!

Top comments (0)

😍 Want to help the DEV Community feel more like a community? 🥹

Head over to the Welcome Thread and greet some new community members!