diff --git a/src/components/CodeSnippet.js b/src/components/CodeSnippet.js index 9f6b82615..fb8c0d27c 100644 --- a/src/components/CodeSnippet.js +++ b/src/components/CodeSnippet.js @@ -4,6 +4,7 @@ import Highlight, { defaultProps } from 'prism-react-renderer'; import github from 'prism-react-renderer/themes/github'; import styles from './CodeSnippet.module.scss'; import cx from 'classnames'; +import useFormattedCode from '../hooks/useFormattedCode'; const copyCode = (code, setCopied) => { const textArea = document.createElement('textarea'); @@ -18,6 +19,7 @@ const copyCode = (code, setCopied) => { const CodeSnippet = ({ children, copy, className, lineNumbers }) => { const language = className.replace('language-', ''); const [copied, setCopied] = useState(false); + const formattedCode = useFormattedCode(children); return (
@@ -25,7 +27,7 @@ const CodeSnippet = ({ children, copy, className, lineNumbers }) => { {({ style, tokens, getLineProps, getTokenProps }) => ( diff --git a/src/hooks/useFormattedCode.js b/src/hooks/useFormattedCode.js new file mode 100644 index 000000000..a559e765e --- /dev/null +++ b/src/hooks/useFormattedCode.js @@ -0,0 +1,14 @@ +import { useMemo } from 'react'; +import formatCode from '../utils/formatCode'; + +const useFormattedCode = (code, options) => { + return useMemo(() => { + try { + return formatCode(code, options); + } catch (e) { + return code; + } + }, [code, options]); +}; + +export default useFormattedCode;