Having the following code snippet that works fine with React + Javascript:
import React, { useRef } from "react";
import Editor from "@monaco-editor/react";
function App() {
const editorRef = useRef(null);
function handleEditorDidMount(editor, monaco) {
editorRef.current = editor;
}
function showValue() {
alert(editorRef.current?.getValue());
}
return (
<>
<button onClick={showValue}>Show value</button>
<Editor
height="90vh"
defaultLanguage="javascript"
defaultValue="// some comment"
onMount={handleEditorDidMount}
/>
</>
);
}
export default App;
I need to use it in a React + Typescript app so I have to add types.
What type should be used for editor
?
Tried like this:
function handleEditorDidMount(editor: HTMLInputElement) {
editorRef?.current = editor;
}
function showValue() {
// eslint-disable-next-line no-alert
alert(editorRef?.current?.getValue());
}
For the first method, the error is:
The left-hand side of an assignment expression may not be an optional property access.ts(2779)
const editorRef: React.MutableRefObject<null>
For the second:
Property 'getValue' does not exist on type 'never'.ts(2339)
Any suggestions?
The returned type of useRef(null)
is React.MutableRefObject<null>
. But you want typescript to know you're gonna pass an input element to the ref, so you have to explicitily set its type const editorRef = useRef(null) as React.MutableRefObject<null | HTMLInputElement>;
const editorRef = useRef(null) as React.MutableRefObject<null | HTMLInputElement>;
editorRef.current
will always be defined, but the type of editorRef.current
is now null | HTMLInputElement
null | HTMLInputElement
, because the type of current is the type you pass into the generic of React.MutableRefObject
.
Regarding this error.
The left-hand side of an assignment expression may not be an optional property access.ts(2779)
const editorRef: React.MutableRefObject<null>
editorRef.current
will always be defined. The value however can be null
as you have explicitily typed. So no need for the ?
Knowing this you can adjust your last part of code to
function showValue() {
// eslint-disable-next-line no-alert
alert(editorRef.current?.getValue());
}
import type onMount
import MonacoEditor, { OnMount } from "@monaco-editor/react";
if you hover on onMount
:
type OnMount = (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => void
use it on handleDidMount:
const handleEditorDidMount:OnMount=(editor) { editorRef?.current = editor; }
if you see the type, handleEditorDidMount
takes 2 args
const handleEditorDidMount:OnMount=(editor,_monaco) {
editorRef?.current = editor;
}
Since you are using OnMount
type, args type will be inferred by typescript:
editor: editor.IStandaloneCodeEditor
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.