Implementing Keyboard Shortcuts with useRef and useEffect
Last Updated :
29 Apr, 2024
Keyboard shortcuts can help you to speed up your work as compared to using a mouse or Touch surface. With just a few key presses, you can perform tasks or actions that would otherwise demand multiple mouse movements and clicks. You can navigate through various User interfaces, switch between applications, or traverse through the documents using keyboard shortcuts. You should write your code in such a way that it supports keyboard shortcuts thus making your website more accessible.
Prerequisite:
Syntax:
target.addEventListener(eventName, callback [, options]);
- target: Specify the DOM element to which you want to bind an event listener.
- eventName: Specify the case-sensitive event name as a string to listen for, such as "click", "scroll", "keydown" etc.
- callback: Specify the function which will get executed when the event occurs.
- options (optional): Provide an optional object which specifies features about an event listener. The possible values are passive,capture,once and signal.
useRef Hook
The useRef allows us to create mutable references to the DOM elements such as buttons, input elements etc.Using useRef we can get access to the DOM elements and attach event listeners to them.
useEffect Hook
In functional Components, the useEffect hook allows us to perform any side effects, such as fetching data, setting and clearing timers or adding and removing event listeners.
Listening for Keyboard Events
Inside the useEffect hook, we can register event listeners for keyboard events such as key down, key up.
We can listen for specific key combinations and trigger an action when the event occurs.
For example, If you press the "Tab" key the control will move to the next focusable element in your webpage.
Executing Actions
Upon detection of the keyboard event related to the keyboard shortcut,we can execute the actions.
Steps to Create a React App
Step 1: Create a new React.js project and install the required dependencies:-
npx create-react-app quick-find-react-app
Step 2: Navigate to the root directory of your project using the following command.
cd my-react-app
Project Structure:
folder structureExample: In this example to create "SearchUsers" component inside the "SearchUsers.js" file. This component displays both a search bar and a list of users data which is being fetched from the API. When user presses Ctrl + / on their keyboard, the focus directly moves to the search input , allowing you to quickly start the search process.
JavaScript
// FileName SearchUsers.js
import React, {
useState,
useEffect,
useRef,
useCallback
} from 'react';
function SearchUsers() {
const [users, setUsers] = useState([]);
const [queryInput, setQueryInput] = useState('');
const [filteredItems, setFilteredItems] = useState([]);
const inputRef = useRef();
const keyDownHandler = e => {
if (e.ctrlKey && e.key === '/') {
inputRef.current.focus();
}
};
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => {
setUsers(json);
setFilteredItems(json);
});
const handle = document.addEventListener('keydown', keyDownHandler);
return () => {
document.removeEventListener('keydown', handle);
};
}, []);
const handleSearchbarInputChange = useCallback((event) => {
const query = event.target.value;
setQueryInput(query);
const result = users.filter(user =>
user.name.toLowerCase().includes(query.toLowerCase())
);
setFilteredItems(result);
}, [users]);
return (
<>
<input
type="text"
placeholder="Type CTRL + / to search"
ref={inputRef}
value={queryInput}
onChange={handleSearchbarInputChange}
/>
<ul>
{filteredItems.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</>
);
}
export default SearchUsers;
Output:
outputConclusion
In conclusion, You can enhance user accessibility and experience by adding keyboard shortcuts into your react application.In this example , We have implemented how to add a keyboard shortcut for the searchbar but you can expand this feature to various other parts of the application. Just we have to be careful that custom keyboard shortcuts do not conflict with system shortcuts.
It would be seamless user experience if all the functionality in webpage is available with the keyboard. Imagine, Users can access and traverse between links, buttons, checkboxes, dropdown menu, forms, and other controls using the Tab key and other keystrokes.
Similar Reads
Building a Dashboard with Dynamic Data Updates Using useEffect
This article is about building a Dashboard with Dynamic Data Updates using useEffect hook. In this project, I have used a weather API that fetches weather details of different cities. I took five cities fetched the weather data of each city in 6-second intervals and displayed the weather details on
3 min read
Fetching Data from an API with useEffect and useState Hook
In modern web development, integrating APIs to fetch data is a common task. In React applications, the useEffect and useState hooks provide powerful tools for managing asynchronous data fetching. Combining these hooks enables fetching data from APIs efficiently. This article explores how to effectiv
4 min read
Implementation of React.memo() and useMemo() in React
React.memo allows functional component to have same optimization as Pure Component provides for class-based components. useMemo is for memoizing function's calls inside functional component. What is React.memo() ?React.memo() is a higher-order component (HOC) provided by React that memoizes function
3 min read
Implementing Global State Management with useContext
The useContext hook is a powerful addition introduced in React 16.8. It allows you to share context (or some value) with all the child elements within a context provider. This is particularly useful when you want to access data or state in child components without manually passing props down to each
4 min read
What is useLayoutEffect, and how is it different from useEffect?
`useLayoutEffect` runs synchronously right after all DOM changes, which makes it perfect for tasks that need access to the DOM before any visual updates occur, like measuring element size or position. On the other hand, `useEffect` runs asynchronously after the browser has finished painting changes,
2 min read
How to use useRef to Access & Interact with DOM eElements ?
In React, useRef is a Hook that provides a way to create mutable references to DOM elements or other React elements. It allows you to access and interact with these elements directly without manually querying the DOM. In this article, we'll explore how to use useRef to work with DOM elements effecti
3 min read
Mutable and Immutable useRef Semantics with React JS
The useRef hook in React.js is essential for preserving references to DOM nodes or persistent values across renders. It accommodates both mutable and immutable values, influencing React's re-rendering behavior based on whether changes are made to mutable or immutable properties of the useRef hook. T
3 min read
Handling Error using React useState and useEffect Hooks
In React, handling error states is very important to provide a smooth user experience and handle unexpected errors that may occur during data fetching or asynchronous operations. By using the useState and useEffect hooks, you can easily manage error states in your React applications. In this article
3 min read
Difference Between useState and useEffect Hook in ReactJS
ReactJS is the powerful JavaScript library used for building user interfaces especially single-page applications(SPAs). Two of the most commonly used hooks in React are useState and useEffect. These hooks make functional components more powerful by allowing them to manage the state and handle side e
3 min read
Difference Between useEffect and useLayoutEffect Hook in ReactJS
In this article, we will learn about the differences between useEffect and useLayoutEffect in React with the help of an example. We will create a counter and implement it using both useEffect and useLayoutEffect to understand the differences practically. useEffectThe useEffect is used to perform sid
5 min read