Last active
January 12, 2023 07:35
-
-
Save stavros-melidoniotis/9128f6d272dc447a57e878a2771997d8 to your computer and use it in GitHub Desktop.
React component for searching values inside an array & highlighting matching keywords
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dummy data, replace with your actual data from an API call etc. | |
const people = [ | |
{ | |
id: 1, | |
name: "Tony Stark", | |
}, | |
{ | |
id: 2, | |
name: "Peter Parker", | |
}, | |
{ | |
id: 3, | |
name: "Bruce Banner", | |
}, | |
{ | |
id: 4, | |
name: "Captain America", | |
}, | |
{ | |
id: 5, | |
name: "Mary Jane", | |
}, | |
{ | |
id: 6, | |
name: "Klark Kent", | |
}, | |
]; | |
export default people; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import people from "./data"; | |
const SearchBar = () => { | |
const [searchValue, setSearchValue] = useState(""); | |
const searchResults = | |
searchValue.trim().length > 0 | |
? people.filter((person) => { | |
const name = person.name; | |
return name | |
.toLocaleLowerCase() | |
.includes(searchValue.toLocaleLowerCase()); | |
}) | |
: []; | |
return ( | |
<div className="flex flex-col"> | |
<input | |
type="text" | |
placeholder="Search..." | |
value={searchValue} | |
onChange={(e) => { | |
setSearchValue(e.target.value); | |
}} | |
/> | |
{searchResults.length > 0 ? ( | |
<ul> | |
{searchResults.map((result) => { | |
return ( | |
<li | |
key={result.id} | |
className="mb-4" | |
dangerouslySetInnerHTML={{ | |
__html: result.name.replace( | |
searchValue, | |
`<b>${searchValue}</b>` | |
), | |
}} | |
></li> | |
); | |
})} | |
</ul> | |
) : null} | |
</div> | |
); | |
}; | |
export default SearchBar; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment