buttons icon indicating copy to clipboard operation
buttons copied to clipboard

refactor : Remove potential issues by replacing flushSync and passing ButtonComponents as props directly

Open maxiim3 opened this issue 2 years ago • 2 comments

A little improvement :

 {BUTTONS?.map((Comp) => {
        return (
            <CardComponent
                key={Comp.name}
                ChildComponent={Comp} />
        );
    })}

I had to make the Home component "client" to avoid SSR issues. I removed getCode function that uses flushSync. Instead I wrapped the ChildComponent (Button) into a div and added a parentRef reference. So I could target the ChildNode and extract the HTML code as string using outerHTML.

const parentRef = useRef<HTMLDivElement>(null);
//...
const onCopy = () => {
        const code = parentRef.current?.childNodes[0]!
        const htmlElement = ReactDOM.findDOMNode(code)! as Element
        const html = htmlElement.outerHTML
        //...
        navigator.clipboard.writeText(html);
        //...
    };
//....
 <div ref={parentRef}  >
      <ChildComponent />
  </div>

Node that I forgot to make a separate commit for the formatting caused by my IDE, so that there are a lot of changes due to space and formatting. Sorry about that...

TButton is just a type for the exported BUTTONS

export type TButton = (() => JSX.Element);
export const BUTTONS: TButton[] = [

maxiim3 avatar Feb 15 '24 11:02 maxiim3

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
buttons ❌ Failed (Inspect) Feb 15, 2024 11:19am

vercel[bot] avatar Feb 15 '24 11:02 vercel[bot]

Hi @maxiim3 ,

Thanks for your contribution! I noticed you're using ReactDOM.findDOMNode, which is deprecated too. Using callback refs or forwarded refs to access the DOM node could be a better choice.

ibelick avatar Mar 06 '24 09:03 ibelick