How to use DOMpurify?

9k views Asked by At

Also I try to use React Stack Snippet but that doesn't work. It's the first time for me so I need help for sure

class App extends Component {
  state = {
    text: sampleText,
  };

  handleChange = (e) => {
    const text = e.target.value;
    this.setState({ text: text });
  };

  renderText = (text) => marked(text, { sanitize: true });

  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-sm-6">
            <textarea
              onChange={this.handleChange}
              value={this.state.text}
              className="form-control"
              rows="35"
            ></textarea>
          </div>
          <div className="col-sm-6">
            <div
              dangerouslySetInnerHTML={{
                __html: this.renderText(this.state.text),
              }}
            ></div>
          </div>
        </div>
      </div>
    );
  }
}

ReactDOM.render(
    <App />,
    document.body
);
<script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I realised an edit markdown. I would like replace "sanitize" by DOMPurify. How can I do that ? I showned this page : enter link description here but I don't know how to adapt my code. I hope It's clear enougth

import './App.css';
import { sampleText } from './sampleText';
import { marked } from 'marked';

import React, { Component } from 'react';

class App extends Component {
  state = {
    text: sampleText,
  };

  handleChange = (e) => {
    const text = e.target.value;
    this.setState({ text: text });
  };

  renderText = (text) => marked(text, { sanitize: true });

  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-sm-6">
            <textarea
              onChange={this.handleChange}
              value={this.state.text}
              className="form-control"
              rows="35"
            ></textarea>
          </div>
          <div className="col-sm-6">
            <div
              dangerouslySetInnerHTML={{
                __html: this.renderText(this.state.text),
              }}
            ></div>
          </div>
        </div>
      </div>
    );
  }
}

export default App;

1

There are 1 answers

0
fernandomatiasdv On

Replace

dangerouslySetInnerHTML={{
                __html: this.renderText(this.state.text),
}}

with `// import purify from “dompurify”;

<div dangerouslySetInnerHTML={{ __html:purify.sanitize(this.state.text, { sanitize: true }) }} />`