christianalfoni / markdown-to-react-components

Convert markdown into react components
MIT License
132 stars 16 forks source link

Highlighting doesn't work when rendering through server #5

Open bebraw opened 9 years ago

bebraw commented 9 years ago

It returns just code element. By the looks of it, CodeComponent does just

this.refs.code.getDOMNode().innerHTML = hljs.highlight(this.props.language, this.props.code).value;

on componentDidMount and componentDidUpdate.

There has to be some better way to deal with this.

bebraw commented 9 years ago

I ended up with

var React = require('react');
var hljs = require('highlight.js');

var CodeComponent = React.createClass({
  componentWillMount: function () {
    this.highlight();
  },
  componentDidUpdate: function () {
    this.highlight();
  },
  highlight: function () {
    var language = this.props.language;
    var code = this.props.code;

    this.setState({
      highlightedCode: hljs.highlight(language, code).value
    });
  },
  render: function () {
    var highlightedCode = this.state.highlightedCode || '';

    return React.createElement('pre', {key: this.props.key},
      React.createElement('code', {
        dangerouslySetInnerHTML: {__html: highlightedCode}
      })
    );
  }
});

module.exports = CodeComponent;

There's possibly a nicer way to deal with it. dangerouslySetInnerHTML is a little meh always.

christianalfoni commented 8 years ago

You want to create a pull on this? It is at least a step forward :-)