Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Last active July 22, 2020 09:23
Show Gist options
  • Select an option

  • Save heytulsiprasad/6be8c8989636cc33ae84ba6ad51e89c5 to your computer and use it in GitHub Desktop.

Select an option

Save heytulsiprasad/6be8c8989636cc33ae84ba6ad51e89c5 to your computer and use it in GitHub Desktop.
How to copy to clipboard and paste?
import React, { Component, createRef } from "react";
class Input extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
copyMsg: "Copy to Clipboard",
isCopied: false,
};
this.inputRef = createRef();
}
inputHandler = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = (e) => {
e.preventDefault();
alert(`Welcome ${this.state.name} 🎉`);
};
copyToClipboard = (e) => {
this.inputRef.current.select();
document.execCommand("copy");
e.target.focus();
this.setState((state) => ({
...state,
copyMsg: "Copied!",
isCopied: true,
}));
setTimeout(() => {
this.setState((state) => ({
...state,
copyMsg: "Copy to Clipboard!",
isCopied: false,
}));
}, 3000);
};
render() {
return (
<div className="p-12">
<form onSubmit={this.submitHandler}>
<label htmlFor="name">What's your name?</label>
<input
id="name"
name="name"
type="text"
ref={this.inputRef}
value={this.state.name}
onChange={this.inputHandler}
/>
<button type="button" onClick={this.copyToClipboard}>
{this.state.copyMsg}
</button>
<button type="submit">Shout Out</button>
</form>
<form>
<label htmlFor="paster">You can try pasting here!!!</label>
<input
type="text"
name="paster"
value={this.state.paster}
onChange={this.inputHandler}
/>
</form>
</div>
);
}
}
export default Input;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment