0

How to convert jQuery code to React JS?

I have a button with text 'Copy'. When I click on it should change its text to 'Copied' and copy to Clipboard. Once copied, after few seconds I want the text to go back to 'Copy'. The following function will work I believe. I want incorporate this function into by React code.

$(function() {
  var $btnCopy = $('#copy-button');

  $btnCopy.on('click', function() {
    var clipboard = new Clipboard('#copy-button');

    clipboard.on('success', function(e) {
      $btnCopy.text('Copied');

      setTimeout(function() {
        $btnCopy.text('Copy');
      }, 2000);
    });
  });
});
class CopyButton extends Component {
  constructor(props) {
    super(props);
    this.state = {
      copyText: 'Copy'
    };
  }

copyToClipboard = () => {
    this.setState({ copyText: 'Copied' });

    const textField = document.createElement('textarea');
    textField.innerText = JSON.stringify(this.props.content);
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
  };

render() {

    return (
      <Container>
        <Header>
          <Title>Testing</Title>
          {this.props.content ? (
            <Fragment>
              <Button primary text="Copy" onClick={this.copyToClipboard}/>
              <Button primary text="View" onClick={this.handleOpen} />
            </Fragment>
        </Header>
      </Container>

export default CopyButton;

Jeena
  • 4,193
  • 3
  • 9
  • 19
  • hey bro you can try this how to set timeout in state here is a post may this help you [link](https://stackoverflow.com/questions/51026090/settimeout-in-react-setstate) – Rampage Programming Jan 31 '20 at 14:33

1 Answers1

2

setState accepts a callback that will be executed after the state is updated, inside the callback you can use setTimeout, something like this:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      copied: false
    }
  }

  copyToClipboard = () => {
    this.setState({copied: true}, () => {
      setTimeout( () => {
        this.setState({copied: false})
    }, 2000)
    })
  }
  render() {
    const btnText = this.state.copied ? 'Copied' : 'Copy'
    return (
      <button onClick={this.copyToClipboard}>
        {btnText}
      </button>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>

For more info check: https://reactjs.org/docs/react-component.html#setstate And When to use React setState callback

Damian Peralta
  • 1,846
  • 7
  • 11