Categories
javascript

How to scroll to line with codemirror-react

This is for "@uiw/react-codemirror": "^4.20.2"

  1. capture the ref to the codemirror objects
<CodeMirror
  ref={scrollDocToView}
  value={editorContent}
  theme={"dark"}
  extensions={[solidity, EditorView.lineWrapping]}
  editable={false}
  basicSetup={{}}
/>

2. on each new ref callback, call the dispatch with the new selection and scrollIntoView

const scrollDocToView = (editor: ReactCodeMirrorRef) => {
  if (!editor || !editor.state?.doc) {
    console.log(`scrollDocToView return`)
    return
  }
  
  // ... calc selection

  let selection: EditorSelection
  selection = EditorSelection.single(fromChar, toChar)

  // dispatch the new selection

  editor!!.view?.dispatch({
    selection: selection,
    scrollIntoView: true,
  })
}

note: I used MUI accordion, and for that the useRef didn’t seem to update when I collapsed and expanded the Accordion. Therefore I needed to update the object that was returned from the ref={} callback.