user-avatar

Kyle J. Roux

jstacoder

Developer Program Member

a python/javascript/php/linux guru ready to take on the world...

CasePeer
orange, CA, USA
https://jstacoder.github.io

Hi
Home

Customize React-Live Editor

1 min read

Why do i want to replace the react-live Editor?

Because I like using react-live for these cool live code examples.

cool huh?

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.

Investigation

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.

Start coding

Now that we know what to do lets start by redefining the editor to use Ace.

editor.jsx
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 (
<AceEditor
width={'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.

live-editor.jsx
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:

pre.jsx
import {LiveError, LivePreview, LiveProvider} from 'react-live'
import { LiveEditor } from './editor'
export default ({code})=>(
<LiveProvider code={code}>
<LivePreview/>
<LiveEditor/>
<LiveError/>
</LiveProvider>
)
Comments
Home