skip to Main Content

How to highlight a word on mouseover in text in a React app

const text = data[data.length - 1] !== undefined ? data[data.length - 1].taskText : null;

 const [hilightWord, setHilightWord] = useState(false);

  const hightlight = (text, hilightWord) => {
    if (!hilightWord) return text;

    const regex = new RegExp(`(${hilightWord})`, "gi");

    return text.split(regex).map((substring, i) => {
      return (
        <span className={styles.highlight} key={i}>
          {substring}
        </span>
      );
    });
  };


<p className={styles.text} onMouseMove={() => setHilightWord(true)} onMouseLeave={() => setHilightWord(false)}>{hightlight(text, hilightWord)}</p>

3

Answers


  1. Not sure if this is exactly your requirement, but it seems like you want the text to be highlighted on mouseover. A really easy way to achieve this is by using CSS :hover selector (this wont even require any JavaScript).

    Implementation:

    return (
       <span className="word" key={i}>
          {substring}
       </span>
    );
    

    CSS:

    .word:hover{
       background-color: #FFFF00;
      /*Add your highlight styles*/
    }
    
    Login or Signup to reply.
  2. In your styles variable add this.

    const styles = {
      ....
      highlight: {
        backgroundColor: '#000000',
        '&:hover': {
          backgroundColor: '#ff0000',
        }
      }
      ....
    };
    
    Login or Signup to reply.
  3. You could spit() your sentence, then wrap it in some DOM element (em for example), then you can use some CSS to set a :hover color on the words.

    Small example:

    const Highlight = ({ text }) => {
        const splitted = text.split(' ');
        return splitted.reduce((p, c) => ([ ...p, ' ', <em>{c}</em> ]), []);
    }
    
    const Example = () => {
        return (
            <div>
                <h1>{'Highlight Example'}</h1>
                <Highlight text={'Hello world! How are you today?'} />
            </div>
        )
    }
    ReactDOM.render(<Example />, document.getElementById("react"));
    em { font-style: unset; }
    em:hover { background-color: yellow; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="react"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search