How can I use a lifecycle method such as ComponentDidMount inside a function below?
var React = require('react');
module.exports = function SectionalSquareComponent(props) {
return (
<div .....
How can I use a lifecycle method such as ComponentDidMount inside a function below?
var React = require('react');
module.exports = function SectionalSquareComponent(props) {
return (
<div .....
You need to extend the React.Component class if you want to use the lifecycle function. As @xadm mentioned, you cannot use a functional component and lifecycle hooks.
Using the ES5 syntax as in your question, this could look like:
var createReactClass = require('create-react-class');
module.exports = createReactClass({
componentDidUpdate: function(prevProps, prevState) {
},
render: function() {
return (<div>...</div>);
}
});
As others have said you need to use react.component if you want to hook into lifecycle methods.
An interesting alternative, if you are completely focussed on functional components, is to use recompose.lifecycle method, so you can do (from docs):
const PostsList = ({ posts }) => (
<ul>{posts.map(p => <li>{p.title}</li>)}</ul>
)
const PostsListWithData = lifecycle({
componentDidMount() {
fetchPosts().then(posts => {
this.setState({ posts });
})
}
})(PostsList);