Fix: Pass Copied Content as prop

Add prop to fence component called content which will
hold the content contained within the fence component.

Update code snippet component so that it filters the fence components
passed to it as children to only display the fence component that
is same language as the selected language and pass the content prop
of the fence component to the copy code button component on each
render of the snippet component.
This commit is contained in:
Stevan Freeborn
2023-04-26 19:31:15 -05:00
parent 538d5f675b
commit 1c5d57e4ed
2 changed files with 23 additions and 21 deletions
+22 -21
View File
@@ -3,12 +3,17 @@
import React, {
Children,
MouseEvent,
ReactElement,
ReactNode,
useState,
} from 'react';
import styles from './CodeSnippet.module.css';
function CodeSnippetCopyButton() {
function CodeSnippetCopyButton({
copyText,
}: {
copyText: string;
}) {
const [copyButtonTooltip, setCopyButtonTooltip] =
useState<boolean>(false);
@@ -21,13 +26,7 @@ function CodeSnippetCopyButton() {
setCopyButtonTooltip(false);
}, 1000);
const target = e.currentTarget;
const code =
target.parentElement?.parentElement?.parentElement?.parentElement?.querySelector(
'pre'
)?.innerText ?? '';
navigator.clipboard.writeText(code);
navigator.clipboard.writeText(copyText ?? '');
};
return (
@@ -130,6 +129,17 @@ export default function CodeSnippet({
setSelectedLanguage(e.target.value);
};
const code = Children.toArray(children)
.filter(
child =>
React.isValidElement(child) &&
child.props.className ===
`language-${selectedLanguage}`
)
.map(child => {
return child as ReactElement;
})[0];
const snippetLanguages = Children.toArray(children).map(
child => {
if (React.isValidElement(child)) {
@@ -165,22 +175,13 @@ export default function CodeSnippet({
<div className={styles.spacer} />
</>
) : null}
<CodeSnippetCopyButton />
<CodeSnippetCopyButton
copyText={code.props.content}
/>
</div>
</div>
<div className={styles.snippetContent}>
<pre>
{Children.toArray(children)
.filter(
child =>
React.isValidElement(child) &&
child.props.className ===
`language-${selectedLanguage}`
)
.map(child => {
return child;
})}
</pre>
<pre>{code}</pre>
</div>
</div>
);
+1
View File
@@ -21,6 +21,7 @@ export default function Fence({
<code
className={`language-${language}`}
dangerouslySetInnerHTML={{ __html: html }}
content={content}
></code>
);
}