Skip to content

Instantly share code, notes, and snippets.

@Manoz
Last active August 11, 2018 15:49
Show Gist options
  • Save Manoz/781d0137156723ec25121a7050f80427 to your computer and use it in GitHub Desktop.
Save Manoz/781d0137156723ec25121a7050f80427 to your computer and use it in GitHub Desktop.
React set class when component is loaded
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