Filter function containsSearchTerm expecting an item and a user-inputted search term, efficiently navigating arrays.Its versatility extends to selecting properties from item objects for searching purposes. In our example, we use two terms—title and description—yet it seamlessly adjusts to accommodate more.
Leveraging JavaScript’s array methods, our filter function swiftly sorts through items. It converts search terms to lowercase for a case-insensitive search. By utilizing the some method, we ensure items matching any specified property remain within the filtered results.
function containsSearchTerm(item, searchTerm) { const { title, description } = item; const lowerCasedSearchTerm = searchTerm.toLowerCase(); return ( [title, description].some(str => str.toLowerCase().includes(lowerCasedSearchTerm)) ); }
Looking ahead, let’s explore how this function integrates within a React application for filtering a list of items based on user input.
App.js
import * as React from "react"; const items = [ { title: "React", description: "React (also known as React.js or ReactJS) is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies." }, { title: "JavaScript", description: "JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification. It is widely used to make web pages interactive and provide online programs, including video games." }, ]; function containsSearchTerm(item, searchTerm) { const { title, description } = item; const lowerCasedSearchTerm = searchTerm.toLowerCase(); return ( [title, description].some(str => str.toLowerCase().includes(lowerCasedSearchTerm)); ); } export default function App() { const [searchTerm, setSearchTerm] = React.useState(""); const inputRef = React.useRef(); React.useEffect(() => { inputRef.current.focus(); }, []); const handleChange = event => { setSearchTerm(event.target.value); }; const filteredItems = items.filter(item => containsSearchTerm(item, searchTerm) ); return ( <>
{description}
Within this React component, we utilize the containsSearchTerm function to filter items based on the user’s input. The useState hook manages the search term state, while the useRef hook focuses the input field during component mounting..
This configuration establishes a dynamic filtering mechanism, enhancing user experience and interaction with the application. By implementing such optimized solutions, developers can ensure robust functionality while maintaining code clarity and efficiency.