/** * Copyright (c) 2013-present, Facebook, Inc. * * @emails react-core */ 'use strict'; import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import Remarkable from 'remarkable'; // TODO: switch back to the upstream version of react-live // once https://github.com/FormidableLabs/react-live/issues/37 is fixed. import {LiveProvider, LiveEditor} from '@gaearon/react-live'; import {colors, media} from 'theme'; import MetaTitle from 'templates/components/MetaTitle'; const compile = code => Babel.transform(code, {presets: ['es2015', 'react']}).code; // eslint-disable-line no-undef class CodeEditor extends Component { constructor(props, context) { super(props, context); this.state = this._updateState(props.code); } componentDidMount() { // Initial render() will always be a no-op, // Because the mountNode ref won't exist yet. this._render(); } componentDidUpdate(prevProps, prevState) { if (prevState.compiled !== this.state.compiled) { this._render(); } } render() { const {children, code} = this.props; const {error} = this.state; return (
{children && (
{children}
)}
Live JSX Editor
{error && (
Error
                  {error.message}
                  {!window.Babel &&
                    ' (try checking your ad blocker if you have one).'}
                
)} {!error && (
Result
)}
); } _render() { if (!this._mountNode) { return; } const {compiled} = this.state; try { // Example code requires React, ReactDOM, and Remarkable to be within scope. // It also requires a "mountNode" variable for ReactDOM.render() // eslint-disable-next-line no-new-func new Function('React', 'ReactDOM', 'Remarkable', 'mountNode', compiled)( React, ReactDOM, Remarkable, this._mountNode, ); } catch (error) { console.error(error); this.setState({ compiled: null, error, }); } } _setMountRef = ref => { this._mountNode = ref; }; _updateState(code) { try { return { compiled: compile(code), error: null, }; } catch (error) { console.error(error); return { compiled: null, error, }; } } _onChange = code => { this.setState(this._updateState(code)); }; } export default CodeEditor;