Search code examples
javascriptreactjsweb-deploymentace-editor

Error: Function components cannot have string refs. We recommend using useRef() instead


Im using ace Editor in my react app and am getting the above error. I want to put the contents of the Ace Editor IDE that im using in my react app from a function call which is triggered through a submit button.

<AceEditor
ref='aceEditor'
height='100%'
width='100%'
mode={ideLanguage}
theme={ideTheme}
fontSize={ideFontSize}
showGutter={true}
showPrintMargin={false}/>

And this is the button

<Button
type='button'
buttonStyle='btn--primary--normal'
buttonSize='btn--medium'
onClick={SendCode}
>SUBMIT</Button>

And this is the function

const SendCode = () => {
  console.log(this.refs.aceEditor.editor.getValue());
};

What am I doing wrong??


Solution

  • String refs are legacy way to set a DOM reference.

    With latest React release, it is advisable to use React.useRef() hook for functional components and React.createRef() for class components.

    You can read more details at - https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs

    And I can guess, you might have turned on the strict mode with <React.StrictMode> higher-order component. Thats' why there is an error/warning thrown.

    What you should do -

    1. Declare a ref variable.

      const aceEditorRef = useRef();

    2. After that , replace ref='aceEditor' with ref={aceEditorRef} .

      <AceEditor
        ref={aceEditorRef}
        height='100%'
        width='100%'
        mode={ideLanguage}
        theme={ideTheme}
        fontSize={ideFontSize}
        showGutter={true}
        showPrintMargin={false}/>
    
    1. Use aceEditorRef.current to get DOM reference

      const SendCode = () => {
        console.log(this.aceEditorRef.current.editor.getValue());
      };