2

Very new to react, I have a class like:

export const Checkbox = ({ label, className }) => {
  ....
  .... 
  return(
    .............
    .............

  );             
}

In such a class how can I specify add a componentDidMount and componentWillReceiveProps?

Edit:

I have a layman's doubt, which is the correct way to create a wrapper react component for checkbox? functional component or by extending from Component? If I create a Checkbox wrapper component for others to use, will it be possible for them to connect to a store (say redux) from their pages?

Thanks, Santhosh

Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
kallada
  • 1,829
  • 4
  • 33
  • 64
  • 1
    You cannot. That's actually invalid syntax. You would want to replace render with return. To utilize lifcycle methods use must create a class which extends React.Component – pizzarob Aug 18 '17 at 22:39

3 Answers3

3

You can't.

These are functional components and do not support React's lifecycle methods.

If you want to use React's lifecycle methods, you need a class that inherits from React.Component

See example below.

class Example extends React.Component {
    
   componentDidMount(){
     //code here
   }
    
}

Here is a good answer explaining the differences and when to use functional over class components.

UPDATE from React 16.8

Lifecycle methods can now be used with the introduction of hooks.

If you wished to implement componentDidMount you would use the useEffect hook and pass an empty array as the second argument. An example would look like as follows.

const Example = () => {
  React.useEffect(() => {
    // do stuff here
  }, []);
}
Community
  • 1
  • 1
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
2

You can't.

If you want to use React's lifecycle methods, you need a class that inherits from React.Component.

export class Checkbox extends React.Component {
    componentDidMount() {
        ....
    }

    render() {
        const { label, className } = this.props;
        ....
    }
}
0xRm
  • 1,259
  • 8
  • 11
  • @ I have a layman's doubt, which is the correct way to create a wrapper react component for checkbox? functional component or by extending from Component? If I create a Checkbox wrapper component for others to use, will it be possible for them to connect to a store (say redux) from their pages? – kallada Aug 18 '17 at 23:06
  • @kalladaYou can use either to create your own wrapper of a checkbox. Redux works with supplying props to a component, so any component that renders based on props will work. – 0xRm Aug 21 '17 at 11:57
  • @paul_fitzgerald I'm a bit confused why your answer, which has literally copied the main sentence from my answer is now changed to the accepted answer. – 0xRm Aug 29 '17 at 14:01
1

You cannot. You should create a class that extends PureComponent or Component if you need lifecycle methods.

john_omalley
  • 1,398
  • 6
  • 13