#ART #BOOK #CODE #DESIGN ©WOODY CHAU:IMAGINE THE POSSIBILITIES 
#ART #BOOK #CODE #DESIGN ©WOODY CHAU:IMAGINE THE POSSIBILITIES 
Code
React
Github
Codepen
Code
2023.03.13
Share

React Clipboard with Additional Text

Sharing information on the internet is a common practice, but sometimes we may encounter a problem where our content is easily copied or reposted. In this case, we need some protection. For example, we want people who copy our content to add source and copyright information, so that we can protect our intellectual property.

In React, we can use a custom Hook to easily implement the functionality of copying content to the clipboard and adding extra text in the web page.

import React, { useEffect } from 'react'; const useCopy = (statement) => { useEffect(() => { const copyHandler = (event) => { const selected = window.getSelection().toString(); event.clipboardData.setData('text/plain', `${selected}\n\n${statement}`); event.preventDefault(); }; document.addEventListener('copy', copyHandler); return () => { document.removeEventListener('copy', copyHandler); }; }, [statement]); }; const CopyWithStatement = ({ statement, children }) => { useCopy(statement); return <>{children}</>; }; export default CopyWithStatement;

Simply pass the content to be copied as a child component to CopyWithStatement, and pass the additional text in statement.

import React from 'react' import CopyWithStatement from './CopyWithStatement' function App() { return ( <CopyWithStatement statement="Read more at https://woodychau.hk © 2023 Woody Chau"> Hello World </CopyWithStatement> ) } export default App

Open Source: Github

React