From 1c5d57e4edb2353152259a5f63a6912412a1d333 Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Wed, 26 Apr 2023 19:31:15 -0500 Subject: [PATCH] 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. --- src/app/components/CodeSnippet.tsx | 43 +++++++++++++++--------------- src/app/components/Fence.tsx | 1 + 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/app/components/CodeSnippet.tsx b/src/app/components/CodeSnippet.tsx index bc5b1fc..901b5b0 100644 --- a/src/app/components/CodeSnippet.tsx +++ b/src/app/components/CodeSnippet.tsx @@ -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(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({
) : null} - +
-
-          {Children.toArray(children)
-            .filter(
-              child =>
-                React.isValidElement(child) &&
-                child.props.className ===
-                  `language-${selectedLanguage}`
-            )
-            .map(child => {
-              return child;
-            })}
-        
+
{code}
); diff --git a/src/app/components/Fence.tsx b/src/app/components/Fence.tsx index 243c768..1fe0631 100644 --- a/src/app/components/Fence.tsx +++ b/src/app/components/Fence.tsx @@ -21,6 +21,7 @@ export default function Fence({ ); }