I am trying to achieve copy to clipboard functionality, which is working fine if I pass type of button to text i.e. type="text"
, but not working when the type of button hidden
.
Here is the link for the codeSandbox https://codesandbox.io/s/priceless-blackburn-irwvw?file=/src/App.js
Note:- Don't want to hide the input with CSS. Please help me to find a solution for that. Thanks in advance.
import React, { useRef, useState } from "react";
export default function App() {
const inputRef = useRef(null);
const [copied, setCopy] = useState(false);
const copy = () => {
setCopy(false);
inputRef.current.focus();
inputRef.current.select();
try {
const successful = document.execCommand("copy");
if (successful) {
setCopy({ copied: "Link Copied!" });
}
} catch (err) {
console.log("err=>", err);
setCopy({ copied: err });
}
};
return (
<div className="App">
<button onClick={copy}>Copy </button>
<input
ref={inputRef}
defaultValue={"https:www.google.com"}
type="hidden"
/>
</div>
);
}