remarkjs / react-markdown

Markdown component for React
https://remarkjs.github.io/react-markdown/
MIT License
13.14k stars 870 forks source link

prismjs highlighting #58

Closed kennetpostigo closed 7 years ago

kennetpostigo commented 7 years ago

Is there a standard way of adding prismjs highlighting to codeblocks?

rexxars commented 7 years ago

There isn't a "standard" way, but it's easy enough...

Loading prism after you've rendered markdown will apply highlighting automatically: http://jsbin.com/xodarebeyi/1/edit?html,js,output

Or if you want to do it in a more javascripty way: http://jsbin.com/mukijamuku/1/edit?html,js,output

Pretty simple, just use a custom renderer for Code and CodeBlock.

tauren commented 7 years ago

If you have a single page app with route changes, codeblocks will only be highlighted on the initial route. You'll need to run highlightAll on each route change. Here's how I'm dealing with it currently, but it may not be the best solution:

/** @jsx h */

import React from 'react'
import Markdown from 'react-markdown'
import Prism from 'prismjs'
import styles from './styles.css'

export default class Readme extends React.Component {

  componentDidMount () {
    Prism.highlightAll()
  }

  componentDidUpdate () {
    Prism.highlightAll()
  }

  render() {
    return (
      <Markdown 
        source={this.props.source} 
        className={styles.readme} 
      />
    )
  }
}

Note that I also have this in my main app.js file:

import Prism from 'prismjs';
import 'prismjs/components/prism-jsx';
import 'prismjs/themes/prism-okaidia.css';
rexxars commented 7 years ago

@tauren You could also use the more programmatic approach, as demonstrated here. Or, if you're open to using something react-lowlight instead of prismjs, you could check out this example for a fully reactified solution.

tauren commented 7 years ago

Yes, I do like the pragmatic approach!

ATM, I don't have a strong preference over prismjs vs highlightjs (with or without react-lowlight). I went with prismjs because it was the first example I found that worked without a ton of effort.

Based on your experience, what would you use for doing syntax highlighting? Since react-lowlight is your project, I'm assuming you would go that route?

rexxars commented 7 years ago

It depends a bit on the use case. I'm a sucker for keeping things fully in the react paradigm, not using dangerouslySetInnerHTML and not altering the DOM outside of React - so that's why I like lowlight. It's also great for live previews, as the virtual DOM diffing works really well in these cases.

I do think prism has some very pretty stylesheets out of the box, and takes a bit less setup, I guess. For more static sites, I might go for that.