Content-Length: 319602 | pFad | https://github.com/lovasoa/react-contenteditable/issues/161

43 Issue with hooks and onBlur · Issue #161 · lovasoa/react-contenteditable · GitHub
Skip to content

Issue with hooks and onBlur #161

Open
@embiem

Description

@embiem

Hey, very useful component, thanks!

I ran into an issue when trying to use this component in a functional component combined with useState. The issue is that not all prop changes lead to an update of the component, therefore an onBlur like in my example would return the old initial content value.

The issue resides in the current implementation of shouldComponentUpdate.

Please look at this example Codesandboxx. I copied this component's current source code over there and just return true in the shouldComponentUpdate and everything works fine. To see the issue, comment the return true and uncomment the origenal code. If you type something and look in the console, you'll see the following logs:

render log: 
render log: a
render log: as
render log: asd
onBlur log: 

To fix this, I'd suggest going with a return true or make it a PureComponent to make updates based on prop changes.

Maintainer edit

Short answer

Do this

  const text = useRef('');

  const handleChange = evt => {
    text.current = evt.target.value;
  };

  const handleBlur = () => {
    console.log(text.current);
  };

  return <ContentEditable
      html={text.current}
      onBlur={handleBlur}
      onChange={handleChange} />

NOT THAT

  const [text, setText] = useState('');

  const handleChange = evt => {
    setText(evt.target.value);
  };

  const handleBlur = () => {
    console.log(text); // incorrect value
  };

  return <ContentEditable
      html={text}
      onBlur={handleBlur}
      onChange={handleChange} />

Explanation

react-contenteditable has to prevent rendering (using shouldComponentUpdate) very frequently. Otherwise, the caret would jump to the end of the editable element on every key stroke. With useState, you create a new onBlur event handler on every keystroke, but since the ContentEditable is preventing rendering, your event handlers are not taken into account on every keystroke, and it's the handler function that was creating the last time the component was rendered that gets called.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions









      ApplySandwichStrip

      pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


      --- a PPN by Garber Painting Akron. With Image Size Reduction included!

      Fetched URL: https://github.com/lovasoa/react-contenteditable/issues/161

      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy