diff --git a/README.md b/README.md index 4038646e5..e82b08367 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,8 @@ export interface ReactCodeMirrorProps extends Omit((props, ref) => { - const { className, value, selection, extensions = [], onChange, theme, height, minHeight, maxHeight, width, minWidth, maxWidth, ...other } = props; + const { className, value, selection, extensions = [], onChange, autoFocus, theme, height, minHeight, maxHeight, width, minWidth, maxWidth, ...other } = props; const editor = useRef(null); const { state, view, container, setContainer } = useCodeMirror({ container: editor.current, - value, theme, height, minHeight, maxHeight, width, minWidth, maxWidth, + value, autoFocus, theme, height, minHeight, maxHeight, width, minWidth, maxWidth, selection, onChange, extensions, diff --git a/src/useCodeMirror.ts b/src/useCodeMirror.ts index 88ac39e2d..5150cfdb5 100644 --- a/src/useCodeMirror.ts +++ b/src/useCodeMirror.ts @@ -12,7 +12,7 @@ export interface UseCodeMirror extends ReactCodeMirrorProps { } export function useCodeMirror(props: UseCodeMirror) { - const { value, selection, onChange, extensions = [], theme = 'light', height = '', minHeight = '', maxHeight ='', width = '', minWidth = '', maxWidth = '' } = props; + const { value, selection, onChange, extensions = [], autoFocus, theme = 'light', height = '', minHeight = '', maxHeight ='', width = '', minWidth = '', maxWidth = '' } = props; const [container, setContainer] = useState(props.container); const [view, setView] = useState(); const [state, setState] = useState(); @@ -73,5 +73,11 @@ export function useCodeMirror(props: UseCodeMirror) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [theme, extensions, height, minHeight, maxHeight, width, minWidth, maxWidth]); + useEffect(() => { + if (autoFocus && view) { + view.focus() + } + }, [autoFocus, view]) + return { state, setState, view, setView, container, setContainer } } \ No newline at end of file diff --git a/website/App.tsx b/website/App.tsx index 8e709d58c..7da6b6862 100644 --- a/website/App.tsx +++ b/website/App.tsx @@ -52,6 +52,7 @@ let count = 0 export default function App() { const [mode, setMode] = useState('javascript'); + const [autofocus, setAutofocus] = useState(false); const [theme, setTheme] = useState('light'); const [code, setCode] = useState(''); const [extensions, setExtensions] = useState(); @@ -104,6 +105,7 @@ export default function App() { height={height} theme={theme} extensions={extensions} + autoFocus={autofocus} className={styles.codemirror} onChange={(value) => { // console.log('value:', value); @@ -124,6 +126,10 @@ export default function App() { }}> change code + /, '')} />