background

In order to enhance user experience, we usually provide a quick search function when using the table list, so that users can quickly locate. However, if fuzzy matching is carried out, we hope that the entered keywords will be highlighted in the searched data to improve user experience

Technical point

When the user searches for keywords, the keywords in the search data are set to different background colors

1. The font tags

<font color="red" size="5" face="arial" > </font>Copy the code

2. DangerouslySetInnerHTML

React provides an alternative to innerHTML for the DOM browser. In general, setting up HTML directly with code is risky because it is easy to unintentionally expose users to cross-site scripting (XSS) attacks. So, you can set HTML directly in React, but when you want to set dangerouslySetInnerHTML, you need to pass it an object with key __html, // Const Test = () => {return <div dangerouslySetInnerHTML={{__html: 'FIRST &middot; '}} / >}Copy the code

Implement core code

Const textHight = (value: string, keyWord:) const textHight = (value: string, keyWord:) string) => { if (value.indexOf(keyWord) ! == -1 && keyWord ! == '') { return value.replace(keyWord, `<font color="yellow">${keyWord}</font>`) } return value } <span dangerouslySetInnerHTML={{__html: TextHight (testString, 'test ')}} />Copy the code

Method 1: Single highlight

const hasSearch = (title: string, search: string) => {
    const index = title.indexOf(search);
    const beforeStr = title.substr(0, index);
    const afterStr = title.substr(index + search.length);
    const titles =
      index > -1 ? (
        <span>
          {beforeStr}
          <span className={styles['highlight']}>
            {search}
          </span>
          {afterStr}
        </span>
      ) : (
        <span>{title}</span>
      );
    return titles;
  };
Copy the code

Method 2: Highlight everything

export const Mark = ({ name, keyword }: { name: string; keyword: string }) => { if (! keyword) { return <>{name}</>; } const arr = name.split(keyword); return ( <> {arr.map((str, index) => ( <span key={index}> {str} {index === arr.length - 1 ? null : ( <span style={{ color: "#257AFD" }}>{keyword}</span> )} </span> ))} </> ); };Copy the code