Skip to content
Advertisement

Hide message after a few seconds in React

The question is about hiding a message after 5 seconds.

In the code below, if I click on the Generate Room Name button , it will generate the url in the textbox. I will be copying that url using the Copy button and a “Copied to clipboard” message will be displayed. I want to hide that message after 5 seconds. Please someone look into it.

import React from 'react';
import FlashMessage from 'react-flash-message'
import Iframe from 'react-iframe';
 export default class CustomView extends React.Component {
 constructor(props) {
 super(props);
  this.state = {
  roomname: '',
  copySuccess: '',
  enablebutton: true
  }
}
 makeid() {
let r = (Math.random() + 1).toString(36).substring(7);
console.log("random", r);
this.setState({
  roomname: r,
  enablebutton: false
})
}
copyToClipboard = (e) => {
this.textArea.select();
document.execCommand('copy');
e.target.focus();
this.setState({ copySuccess: 'Copied!' });
};
render() {
return (
  <div>
    <button onClick={this.makeid.bind(this)}> Generate RoomName</button>
          <div style={{ display: "flex", marginLeft: '19%', marginTop: '-2%' }}>
         <form disabled={this.state.enablebutton}>
         <textarea style={{
          width: "457px",
          height: "15px"
        }} disabled={this.state.enablebutton}
          ref={(textarea) => this.textArea = textarea}
          value={`https://xxxxxxxxx.azurewebsites.net/?roomname=${this.state.roomname}`}/>
      </form>
      {
     document.queryCommandSupported('copy') &&
        <div disabled={this.state.enablebutton}>
          <button onClick={this.copyToClipboard}>Copy</button>
            <p style={{ color: "red" }}> {this.state.copySuccess}</p>
        </div>
      }
        </div>

  </div>
    );
 }
}

Thanks

Advertisement

Answer

It’s enough to clear the copySuccess state after 5000 ms:

copyToClipboard = (e) => {
this.textArea.select();
document.execCommand('copy');
e.target.focus();
this.setState({ copySuccess: 'Copied!' }, () => setTimeout( () => this.setState({ copySuccess: '' }) ,5000));
};
Advertisement