Create Ref using React.createRef without using constructor in React?

deadcoder0904 picture deadcoder0904 · Jan 18, 2019 · Viewed 8.3k times · Source

Basically, I have used constructor in React for only 3 reasons -

1. To initialize state like -

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = { counter: 0 };
    }
}

but due to Babel's class-field support, I don't use it anymore

class App extends React.Component {
    state = { counter: 0 };
}

2. To bind functions like -

class App extends React.Component {
    constructor(props) {
        super(props);
        this.increment.bind(this);
    }

    increment() {

    }
}

but due to arrow functions, I don't do it anymore

class App extends React.Component {
    increment = () => {

    }
}

3. To use createRef like -

class App extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }
}

So can I use React.createRef without using constructor in React?

Answer

Ana Liza Pandac picture Ana Liza Pandac · Jan 18, 2019

You can declare it as an class field just like state.

class App extends React.Component {
  state = { counter: 0 };
  inputRef = React.createRef();
}

Babel will transpile it into something like the code below in stage-2 presets.

constructor(props) {
    super(props);

    this.state = { counter: 0 };
    this.inputRef = React.createRef();
  }