3

I have some text that I want to simply highlight using a simple react package called 'react-animarker'. I have tried to use useState hook as I want to dynamically update the speed of the animation as shown. However, the duration does not change the way I want it to. But in the console, it does show as changing. Any ideas as to why?

Link to React Package: https://github.com/ramonmetzker/react-animarker

import React, {useState} from 'react'
import {Mark} from 'react-animarker'


const Highlightx = () => {

    const [speed, setSpeed] = useState(5)

    const handleClick = () => {
        setSpeed(20)
        console.log(speed);
    }  

  return (
    <>
    <Mark duration={speed}>Highlightx</Mark>
    <button onClick={handleClick}>Hello</button>
    </>
  )
}

export default Highlightx
ckesplin
  • 1,284
  • 1
  • 9
  • 15
rj05
  • 33
  • 5
  • By any chance, do you mean the other way around? The changed `speed` is passed down properly, but the `console.log` shows the original speed? – CertainPerformance Jul 10 '22 at 22:35
  • I had the same question as @CertainPerformance. Using the state value directly after setting it will not show up until the next render, therefore the speed value output on the console.log will be the value of the *current* render - before you set the speed to 20. – ckesplin Jul 10 '22 at 22:38
  • 1
    No, the first time I click, the console shows the original value, but then since the second click it updates properly. It's just the actual highlighter that never updates. – rj05 Jul 10 '22 at 22:39
  • The highlighter itself never resets and starts again after clicking the button. It just continues at the original pace. – rj05 Jul 10 '22 at 22:46
  • Your react code looks alright for changing state . I'm not familiar enough with react-animarker to know if changing properties of will change the state of the highlight. – ckesplin Jul 10 '22 at 22:50
  • @ckesplin Would you be knowing any other plugin or method to progressively highlight text that I could implement in react? Thank you so much for your help. – rj05 Jul 10 '22 at 22:53
  • if you try `const handleClick = () => setSpeed(prev => prev + 20)`, would speed change noticely? – Four Jul 11 '22 at 02:28

1 Answers1

2

After taking a look at the library you are using, I found a solution:

For some reason, React does not see any state change with the <Mark> component when the duration property changes, therefore, React does not force a refresh of the component. If you add a key property that changes with the duration, then it will force a re-render of the Mark component and re-draw your highlight.

ex:

<Mark key={speed} duration={speed}>

Here is simple example in codesandbox (simply change the value of the input field and the highlight will re-draw after each change): example

ckesplin
  • 1,284
  • 1
  • 9
  • 15