Home > OS >  Hide msg after some seconds in react
Hide msg after some seconds in react

Time:04-15

The query is about hiding message after 5 seconds In the given below code , if I click on generate room name button , it will generate the url in textbox , I will be copying that url using copy button and copied 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

CodePudding user response:

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));
};

CodePudding user response:

Modify your copyToClipboard function like this:

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

for more info visit here

  • Related