Skip to content

Commit

Permalink
feat: Format code in code snippet where possible
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Jun 11, 2020
1 parent d6d2238 commit 136389c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/components/CodeSnippet.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -18,14 +19,15 @@ 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 (
<div>
<div className={styles.container}>
<Highlight
{...defaultProps}
theme={github}
code={children}
code={formattedCode}
language={language}
>
{({ style, tokens, getLineProps, getTokenProps }) => (
Expand Down
14 changes: 14 additions & 0 deletions src/hooks/useFormattedCode.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 136389c

Please sign in to comment.