I'm trying to provide search suggestions to users where the value the user has inputted into the search field is highlighted in the suggestion. For example, if we had an array of city name strings, and the user typed "new" into the input, I would want to suggest something like "New York City."
My vanilla JS solution:
const cities = [ 'New York City', 'Boston', 'Seattle', 'Miami' ];
const input = document.querySelector('input');
const searchValue = input.value;
const searchRegEx = new RegExp(searchValue, 'gi');
const filteredCities = cities.filter(city => city.match(searchRegEx));
const suggestions = filteredCities.map(city => city.replace(searchRegEx, '<span class="highlight">$&</span>')).join('');
// Insert suggestions into DOM here...
The problem is I'm working in React and the string of HTML is escaped. I know I can use the dangerouslySetInnerHTML
prop, but it seems discouraged. Is this a valid use case or is there a better way? Thanks for any help!