a python/javascript/php/linux guru ready to take on the world...
1 min read
Because I like using react-live for these cool live code examples.
But i realized that i wasnt a fan of the editor they were using. Im not going to point any fingers... or name any names, but i felt the editing experience could have been a little smoother.
So i decided to try and see if I could use react-ace instead.
First thing is I need to see how react-live has implemented its default editor to see how easy it may or may not be to customize the editor.
Luckily the LiveEditor
component is already a seperate piece of the api, so i can just define a
custom LiveEditor
that uses react-ace. Also i noticed that react-live is using the React context
api to provide data from the editor to the previewer, so this may be eaiser than i had thought.
Now that we know what to do lets start by redefining the editor to use Ace.
export const CodeEditor = ({code, disabled, language, onChange, style, theme})=>{const getCode = useMemo(()=> code, [code])const [editorCode, setEditorCode] = useState(getCode)const updateContent = useCallback(code =>{setEditorCode(code)onChange(code)}, [editorCode])return (<AceEditorwidth={'100%'}value={editorCode}onChange={updateContent}style={style}name="blah"mode={'jsx'}theme="monokai"height="10vh"showGutter={true}/>)}
we just need to be sure that it has the same interface (ie: props) as the one from react-live, that means:
code - the code to edit
disabled - self explanitory
language - what language should be used to define highlighting
onChange - callback for managing a controlled component
style - self explanitory
theme - we wont use this
So if you notice all we are really doing here is wrapping the AceEditor
component to keep the state of the code,
making sure we rerender if it changes.
Now lets redefine the LiveEditor
component that mangages the live context and passes it to our editor.
import React, { useContext } from 'react'import { LiveContext } from 'react-live'import CodeEditor from './editor.jsx'export const LiveEditor = props =>{const {code, language, theme, disabled, onChange} = useContext(LiveContext)return (<CodeEditor{...props}theme={theme}code={code}language={language}disabled={disabled}onChange={onChange}/>)}
So here we are just extracting the context provided by react-live and passing it to our component.
now we can just use it like this:
import {LiveError, LivePreview, LiveProvider} from 'react-live'import { LiveEditor } from './editor'export default ({code})=>(<LiveProvider code={code}><LivePreview/><LiveEditor/><LiveError/></LiveProvider>)