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:
Example: 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.
// 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:
Implementing Keyboard Shortcuts with useRef and useEffect
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.
Contact Us