react-ace icon indicating copy to clipboard operation
react-ace copied to clipboard

AceEditor cannot be used as a controlled component

Open Pika-Pool opened this issue 4 years ago • 1 comments

Versions:

  • "react": "^17.0.2"
  • "react-ace": "^9.5.0"
  • "react-dom": "^17.0.2"
  • "vite": "^2.6.14"

Problem

I'm trying to create non-editable pieces of code in the editor. For this, I'm using a state to store the current input and checking if the value passed in onChange prop matches a RegExp. If it does match, the state is updated, else its not.

Using the value and onChange props, I'm unable to create a controlled editor component. Even when I do not change the value in the value prop, the changes can be seen in the editor

Sample code to reproduce your issue

https://stackblitz.com/edit/vitejs-vite-hg79ng?file=package.json&terminal=dev

Pika-Pool avatar Dec 28 '21 13:12 Pika-Pool

Not the standard way of doing react, but there is a workaround.

  const [_, setInvokeRender] = useState(false);

  const onCodeChange = (newCode: string) => {
    const match = newCode.match(reg);
    if (!match) {
      setInvokeRender((prev) => !prev)
      return;
    }
    setCode(newCode);
  };

irreg avatar Aug 06 '23 00:08 irreg