Last active
August 11, 2018 15:49
-
-
Save Manoz/781d0137156723ec25121a7050f80427 to your computer and use it in GitHub Desktop.
React set class when component is loaded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
class MyComponent extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
didMount: false, | |
}; | |
} | |
componentDidMount() { | |
// componentDidMount() is only executed once so | |
// we're using setInterval() instead of setTimeout() | |
// to schedule it periodically | |
this.delay = setInterval(() => | |
this.setState(prevState => ({ didMount: !prevState.test })), 500); | |
} | |
// Called when a component is being removed from the DOM | |
// Perfect timing to clear our delay | |
componentWillUnmount() { | |
clearInterval(this.delay); | |
} | |
render() { | |
const { didMount } = this.state; | |
return ( | |
<div className={`${didMount && 'loaded'}`}> | |
<p>Hello, World!</p> | |
</div> | |
); | |
} | |
} | |
export default MyComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
setInterval()
documentationcomponentDidMount()
documentationcomponentWillUnmount()
documentation