DEV Community

rabbitzzc
rabbitzzc

Posted on

useEnterCallback

import React, { useEffect, useRef } from 'react';

const useEnterCallback = (callback) => {
  const inputRef = useRef(null);

  useEffect(() => {
    const handleKeyPress = (event) => {
      // deprecated keyCode =  13
      if (event.key === 'Enter' || event.code === 'Enter') {
        callback(inputRef.current.value);
      }
    };

    inputRef.current.addEventListener('keydown', handleKeyPress);

    return () => {
      inputRef.current.removeEventListener('keydown', handleKeyPress);
    };
  }, [callback]);

  return inputRef;
};

const MyComponent = () => {
  const inputRef = useEnterCallback((value) => {
    console.log('Enter pressed! Value:', value);
  });

  return <input ref={inputRef} />;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay