I have a React.js app with a search bar which is similar to, i.e., Google. A user can type some text into an input field, and matching data is fetched and displayed in a dropdown menu below the input.
My issue: I want to bold certain words that are shown in my dropdown - specifically the words in the string that the user has not typed into the input field themselves.
So, for instance, if a user types in the search bar "blue", below it will display all data in the DB which contains the word "blue" i.e. "blue shoes" or "blue sky". I want it that the word that is not typed into the searchbar to be bolded --> sky or shoes
My makeBold function does not work because a) it displays on the browser as <b>blue</b> sky
rather than actually bolded; b) it would bold the keyword the user typed in rather than the other words)
** keyword
is passed to this component by the parent, it contains the text
the user has written in the input field
** searchResults
contains the list of fetched search results passed as an
array of objects
const SearchResults = ({ keyword, searchResults }) => {
const showDropdown = () => {
return searchResults.map((item) => {
if (item.term.includes(keyword.toLowerCase())) {
return (
<div key={item.term}>
<ul>
<li className="input-fields search-results">
{makeBold(item.searchterm)} ({item.nrResults})
</li>
</ul>
</div>
);
}
});
};
const makeBold = (input) => {
var re = new RegExp(keyword, 'g')
return (
input.replace(re, '<b>'+keyword+ '</b>')
)
}
return <div>{keyword ? showDropdown () : null}</div>;
};
So my question is how to bold specific text in my string which has not typed into the input field? Thanks!