react-hooks
react-hooks copied to clipboard
Add `useClipboard` hook
Motivation
When it comes to interacting with the clipboard, multiple options are available. The Clipboard API is not yet widely supported by browsers.
A compatible solution should be available out of the box:
- Try using the new Clipboard API by default
- Fallback to
document.execCommand()
if necessary
Basic example
function Example() {
const { copy, cut, paste } = useClipboard();
const [value, setValue] = useState('foo');
return (
<>
<input value={value} onChange={(e) => setValue(e.target.value)} />
<button type="button" onClick={() => copy(value)}>Copy</button>
</>
);
}
Details
Lack of permissions (e.g. for pasting) should be handled gracefully with opt-in support for error callbacks.
Hey @kripod do you need someone to build that? I could give it a go :)
@maciekgrzybek I would appreciate if you could take the challenge of implementation!
@kripod I'll crack on then :)
@kripod could please explain a little bit more about the 'Details' part? 'Lack of permissions (e.g. for pasting) should be handled gracefully with opt-in support for error callbacks.' Not sure if I understand it. Thanks :)
When using the Clipboard API, permissions should be requested from the user at first. If the user refuses to give them, call an optionally supplied errorCallback
method with the reason as a parameter (e.g. Error object or explanation).
Ok, that makes sense, so I'm guessing I should use this API right? https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions
Or is it native browser behaviour to ask the user for the permission?
I'm not sure about it, as it isn't documented in depth.
Ok thanks, @kripod, I'll investigate it.
@kripod one more thing, what's the approach for developing hooks in this project? is there something like an example page to test it? or do I need to create something external?
@maciekgrzybek Unfortunately, there is no example page to test hooks with, but Jest is being used for writing tests. I am considering migration to a monorepo to resolve #77 and prepare structural requirements for #26.
Hey, I've added PR for this - https://github.com/kripod/react-hooks/pull/85
@maciekgrzybek Thank you for your valuable contribution! In the meantime, the project has been migrated to a monorepo with a package called web-api-hooks
. I would be grateful if you could update your pull request, moving useClipboard
under the aforementioned package.
Unfortunately, I will be busy in the next days due to tasks at university, so I may not be able to review your code immediately. I appreciate your efforts, keep up the nice work!
Hey @kripod I've added it to a new repo :)