0

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 .....
Raymond K
  • 35
  • 7
  • 5
    lifecycles are parts of components/classes, not functional components – xadm Sep 26 '18 at 15:59
  • 1
    Possible Duplicate of [ReactJS lifecycle method inside a functional Component](https://stackoverflow.com/questions/44506207/reactjs-lifecycle-method-inside-a-functional-component/44506265#44506265) – Shubham Khatri Sep 26 '18 at 16:00

2 Answers2

2

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>);
  }
});
ctj232
  • 390
  • 1
  • 9
0

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);
dashton
  • 2,684
  • 1
  • 18
  • 15
  • Why would you import an extra dependency to achieve this instead of following the React "way" of having stateful/class components hook into lifecycle methods and stateless/functional components not? – ctj232 Sep 26 '18 at 23:06
  • 1
    You wouldn't, it's just an interesting alternative and relatively useful library – dashton Sep 27 '18 at 08:36