Home  >  Q&A  >  body text

Replace part of string in WYSIWYG editor using JSX

<p>I have a string provided by WYSIWYG editor input, for example: </p> <pre class="brush:js;toolbar:false;">const originalString = "<div>Some text</div><strong>Some bold text{{response}}</strong> "; </pre> <p>I need to replace <code>{{response}}</code> with some JSX and output the result as HTML. </p> <p>I don't think I can use <code>dangerouslySetInnerHTML</code> because it doesn't handle JSX. Instead, you get the following output: </p> <pre class="brush:html;toolbar:false;"><div>Some text</div> <strong>Some bold text [object Object]</strong> </pre> <p>View examples here. </p> <p>Is there a way to replace <code>{{response}}</code> with JSX and then convert the rest of the string to valid HTML when rendering? </p>
P粉060112396P粉060112396400 days ago470

reply all(1)I'll reply

  • P粉486138196

    P粉4861381962023-08-18 00:37:40

    Is this what you want?

    import React, {renderToString} from "react";
    import "./style.css";
    import * as ReactDOMServer from 'react-dom/server';
    
    export default function App() {
      return (
        <StringReplacement />
      );
    }
    
    class StringReplacement extends React.Component {
      render() {
        //这可以是从所见即所得编辑器中作为字符串的任何有效的HTML
        const originalString = "<div>some text</div><strong>some strong text {{response}}</strong>";
    
        // 用JSX内容替换'{{response}}'
        const jsxReplacement = <span onClick={ () => alert('')}>JSX content here</span>;
        const replacedString = originalString.replace('{{response}}', ReactDOMServer.renderToString(jsxReplacement));
    
        return (
          <div>
            <div dangerouslySetInnerHTML={{ __html: replacedString }} />
          </div>
        );
      }
    }
    
    export default StringReplacement;

    reply
    0
  • Cancelreply