Skip to content

Commit 0cacd87

Browse files
authored
fix: port over isHydrated work to legacy Code component (#1206)
[![PR App][icn]][demo] | CX-2419 :-------------------:|:----------: ## 🧰 Changes Port over [Kevin's work in this PR](#1198) to the legacy markdown `Code` component skipped the Mermaid parts as we don't use that in the legacy markdown for `CodeTabs` ## 🧬 QA & Testing - [Broken on production][prod]. - [Working in this PR app][demo]. [demo]: https://markdown-pr-PR_NUMBER.herokuapp.com [prod]: https://SUBDOMAIN.readme.io [icn]: https://user-images.githubusercontent.com/886627/160426047-1bee9488-305a-4145-bb2b-09d8b757d38a.svg
1 parent 0ec16bd commit 0cacd87

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

components/Code/index.jsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ const copy = require('copy-to-clipboard');
22
const PropTypes = require('prop-types');
33
const React = require('react');
44

5+
const useHydrated = require('../../hooks/useHydrated');
6+
57
// Only load CodeMirror in the browser, for SSR
68
// apps. Necessary because of people like this:
79
// https://github.com/codemirror/CodeMirror/issues/3701#issuecomment-164904534
@@ -39,9 +41,10 @@ CopyCode.propTypes = {
3941

4042
function Code(props) {
4143
const { children, className, copyButtons, lang, meta, theme } = props;
44+
const isHydrated = useHydrated();
4245

4346
const langClass = className.search(/lang(?:uage)?-\w+/) >= 0 ? className.match(/\s?lang(?:uage)?-(\w+)/)[1] : '';
44-
const language = canonicalLanguage(lang) || langClass;
47+
const language = isHydrated ? canonicalLanguage(lang) || langClass : langClass;
4548

4649
const codeRef = React.createRef();
4750

@@ -52,7 +55,9 @@ function Code(props) {
5255
};
5356

5457
const codeContent =
55-
syntaxHighlighter && children ? syntaxHighlighter(children[0], language, codeOpts) : children?.[0] || '';
58+
syntaxHighlighter && children && isHydrated
59+
? syntaxHighlighter(children[0], language, codeOpts)
60+
: children?.[0] || '';
5661

5762
return (
5863
<React.Fragment>

hooks/useHydrated/index.jsx

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const React = require('react');
2+
3+
/**
4+
* A hook that returns whether or not the component has been hydrated.
5+
* Useful for components that should only render in the browser, and not during SSR.
6+
* Waiting to render until after hydration avoids React hydration mismatches.
7+
*/
8+
function useHydrated() {
9+
const [isHydrated, setIsHydrated] = React.useState(false);
10+
React.useEffect(() => setIsHydrated(true), []);
11+
return isHydrated;
12+
}
13+
14+
module.exports = useHydrated;

0 commit comments

Comments
 (0)