DEV Community

Kamran Ayub
Kamran Ayub

Posted on

Copying to the clipboard using React, TypeScript & Material UI

It's common in apps to offer a way to "copy to clipboard" so users can paste content.

I whipped up a quick example using TypeScript and React to make such a behavior that can be applied to any React element using the render props pattern.

You can then use it like this, to wrap <Button /> or any other element:

<CopyToClipboard> {({ copy }) => ( <Button variant="contained" color="primary" onClick={() => copy("some text!")} > Copy </Button>  )} </CopyToClipboard> 

This is using the super simple clipboard-copy package.

You can override the <Tooltip /> props using the TooltipProps prop:

<CopyToClipboard TooltipProps={{ title: "Copied XYZ!", leaveDelay: 3000 }}> 

Enjoy!

Top comments (0)