Render HTML string in isomorphic React app

前端 未结 2 1158
暖寄归人
暖寄归人 2020-12-09 23:12

There is non-SPA scenario with sanitized yet random HTML string as an input:

...

...

&l
2条回答
  •  失恋的感觉
    2020-12-10 00:00

    You can use Babel's API to transform the string into executable JavaScript.

    You can make your life way easier if you ditch the custom component convention, because in JSX they are treated like DOM tags, so if you can make your users use instead of you will save yourself from a lot of trouble.

    I created a working (but ugly) CodeSandbox for you. The idea is to use Babel to compile the JSX to code, then evaluate that code. Be careful though, if users can edit this, they can surely inject malicious code!

    The JS code:

    import React from 'react'
    import * as Babel from 'babel-standalone'
    import { render } from 'react-dom'
    
    console.clear()
    
    const state = {
      code: `
      Hey!
      
      Awesome!
    `
    }
    
    
    const changeCode = (e) => {
      state.code = e.target.value
      compileCode()
      renderApp()
    }
    
    const compileCode = () => {
      const template = `
    function _render (React, Gallery) {
      return (
        
    ${state.code}
    ) } ` state.error = '' try { const t = Babel.transform(template, { presets: ['react'] }) state.compiled = new Function(`return (${t.code}).apply(null, arguments);`)(React, Gallery) } catch (err) { state.error = err.message } } const Gallery = ({ hello }) =>
    Here be a gallery: {hello}
    const App = () => (
    {state.error ? state.error : state.compiled}
    ) const renderApp = () => render(, document.getElementById('root')); compileCode() renderApp()

提交回复
热议问题