Skip to content

Instantly share code, notes, and snippets.

@hellsan631
Last active January 28, 2019 18:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hellsan631/598a4c220078b2485ab77ed3e3384ce7 to your computer and use it in GitHub Desktop.
Save hellsan631/598a4c220078b2485ab77ed3e3384ce7 to your computer and use it in GitHub Desktop.
React Hooks - Prism

React Hooks make including Prism easy.

I've been learning react hooks recently. I love that you can refactor components now and remove a lot of logic that made components giant, and reuse the same logic another components

The example before extrapolates all that behavior of running Prism inside any component.

You can see how I use this for my blog posts on github

import React from 'react'
import ReactMarkdown from 'react-markdown'
import { usePrism } from './Prism';
function Markdown(props) {
const ref = usePrism();
return (
<div ref={ref}>
<ReactMarkdown
{...props}
/>
</div>
)
}
export default Markdown
import Prism from 'prismjs'
import { useRef, useEffect } from 'react'
function _renderNodeList(func, ref) {
const nodeList = ref.querySelectorAll('pre')
for (let i = 0; i < nodeList.length; i++) {
const element = nodeList[i];
func(element)
}
}
function _addAttributes(attribute, ref) {
_renderNodeList((element) => {
element.setAttribute(...attribute)
}, ref)
}
function _addClasses(className, ref) {
_renderNodeList((element) => {
element.classList.add(className)
}, ref)
}
export function usePrism(options) {
const ref = useRef();
useEffect(() => {
withPrism(ref, ...options)
})
}
export function withPrism(
{ current: ref },
plugins = [],
addHooks = () => {},
) {
addHooks(Prism);
plugins.map(({ func, className, dataAttribute }) => {
if (className) {
_addClasses(className, ref);
}
if (dataAttribute) {
_addAttributes(dataAttribute, ref);
}
return func(Prism)
});
Prism.highlightAll()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment