React component - method inside constructor?

When cretaing a React stateful component, is there any problem in putting the component’s method’s inside the constructor instead of using .bind() ?

I mean:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibility: false
    };

    this.toggleVisibility = () => {
      this.setState(state => ({
        visibility: !state.visibility,
      }));
    }
  }

Instead of

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibility: false
    };

    this.toggleVisibility = this.toggleVisibility.bind(this);
  }

  toggleVisibility () {
    this.setState((state) => ({
      visibility: !state.visibility,
    }));
  }

I really prefer the method inside the component because I think it’s more organized, and because I really don’t understand .bind() in depth.

In the curriculum lessons, it’s taught to use .bind(). Is there any problem with doing the other way?

You don’t need bind if you’re using arrow functions as class methods (and it’s a common way to write React class components).
Unfortunately FCC hasn’t enabled class properties, that’s why you can’t use it in curriculum.

1 Like

Thank you very much for the answer.

Actually I’ve been using the methods inside the constructor in the challenges, although the challenges says to use bind(), and it works fine.

What I meant was this:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibility: false
    };
  }

  toggleVisibility = () => {
    this.setState((state) => ({
      visibility: !state.visibility,
    }));
  }

And with class properties enabled you can even get rid of constructor altogether:

class MyComponent extends React.Component {
  state = {
    visibility: false
  };

  toggleVisibility = () => {
    this.setState((state) => ({
      visibility: !state.visibility,
    }));
  }

But anyway, FCC’s React curriculum is outdated and I wouldn’t recommend it as a main source for learning React.

1 Like

Wow, I didn’t know that.

Actually I never worked with React out of FCC yet, so I don’t understand what you mean by “class properties enabled”. You can enable this??

Anyways, what do you recommend for learning React, then?

Any modern tool (create-react-app, next.js) and online editors (codesandbox, codepen) will have them enabled. FCC editor hasn’t.

Spend some $15 and buy some course on Udemy (I personally like courses by Academind because they’re constantly kept up to date).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.