Search code examples
javascripthtmlreactjsprismjs

Import html string on a different file on react. Using prismjs to display code highlighting


Using Prismjs to display code snippets in a design system.

I want to separate the html code sample in a standalone file and import it into my component.

Code sample Component:

CodeSampleContainer.jsx

import React, { Component } from 'react';
import Prism from "prismjs";
import './CodeSample.scss';
import '../Shared/prism.css';

// Import separate html file
import { html } './htmlSnippet.jsx';

class CodeSample extends Component {
  hasHtmlBlob() {
    return (
      <pre>
        <code className="language-html">
          {html} // Any html displayed here will be highlighted by prism
        </code>
      </pre>
      )
    }
  }

  render() {
    return (
      <div className="CodeSample"> 
        {this.hasHtmlBlob()}
      </div>
    )
  }
}

HTML that i want to export:

htmlSnippet.jsx

const html = `
  <div>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>`

return html;

Solution

  • There's two problems in your code:

    JSX syntax

    Instead of declaring your template as a string, you should do it on "react way"

    const html = (
        <div>
            <ul>
               <li>1</li>
               <li>2</li>
               <li>3</li>
            </ul>
        </div>
    );
    

    Export missing

    If you want to export your template from your htmlSnippet.jsx, you should use export, not return.

    export { html };