scniro / react-codemirror2

Codemirror integrated components for React
MIT License
1.66k stars 193 forks source link

Component prop updates are ignored #142

Open andyrichardson opened 5 years ago

andyrichardson commented 5 years ago

Currently, component updates are being ignored

/** @internal */
public shouldComponentUpdate(nextProps, nextState) {
  return !SERVER_RENDERED
}

This means that any update to event handlers just straight up don't work.

In this example, regardless of any calls to setValue, whenever a key is pressed, only the first function passed to CodeMirror is called.

const component = () => {
  const [value, setValue] = useState("old value");

  const handleKeyPress = () => {
    console.log("key pressed - value is", value);
  }

  useEffect(() => {
    setValue("new value")
  }, []);

  // ...
  onKeyPress={handleKeyPress} // The new function is ignored on second render
  // ...
}

Edit: Looks like the issue in this case is due to the way SSR is being detected - I'm trying to use this inside a chrome devtools extension.

Edit 2: Nothing to do with a chrome extension... I've created a PR :+1:

mhuggins commented 4 years ago

I ran into this with onBlur as well. This works if you point to an unchanging function reference (i.e.: class-based components with bound function handlers), but does not work with hooks that have ever-changing function references.

mhuggins commented 4 years ago

There may be a solution that involves useRef for the callback function, but I didn't pursue it too deeply since switching to a class based component resolved it for me.

scniro commented 4 years ago

@andyrichardson @mhuggins I am a lot shorter on time these days as when I started this project. Codemirror & React APIs are moving to quickly for me to keep atop of for the day-to-day. I am looking for a co-maintainer of this project. Please contact me directly if you are interested. Thank you for understanding.

paztis commented 3 years ago

Problem is still here 2 years after. Someone is looking for a solution ?

paztis commented 3 years ago

I've found a way by adding a key on the tag to force reload on props change

ChristopherHButler commented 3 years ago

@paztis did you find a solution? Can this be done with useRef in a functional component?

paztis commented 3 years ago

I add a key to the react component, and the key is equal to the code value. Like this, when the input code change, the component rendering is forced

ChristopherHButler commented 3 years ago

Ahhh ok thanks

hhhluke commented 3 years ago

@paztis but after type in=> code change => cm re-render => the cursor disappear, how did you solve it? thanks