Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 776
deadcoder0904 Avatar asked Jan 18 '19 16:01

deadcoder0904


4 Answers

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();
  }
like image 191
Ana Liza Pandac Avatar answered Oct 05 '22 11:10

Ana Liza Pandac


Yes, you can. For example:

const MyComponent = () => {
  const inputRef = React.createRef();

  return (
    <input ref={inputRef} />
  );
}

The only thing you cannot do, is pass the ref attribute to a functional component:

render() {
  // This won't work.
  return <MyFunctionalComponent ref={this.inputRef} />
}

More info from the official docs, here:

You can, however, use the ref attribute inside a function component as long as you refer to a DOM element or a class component:

like image 29
Chris Avatar answered Oct 05 '22 10:10

Chris


you can create a ref with ref callbacks without using constructor. <input ref={(element) => { this.inputRef = element; }} /> is what you need.

like image 21
Avanthika Avatar answered Oct 05 '22 12:10

Avanthika


On class components write like below:

import React, { Component, createRef } from 'react';

class App extends Component {
  inputRef = createRef();

  render() {
    return (
      <div ref={this.inputRef}~~~
    );
  }
}

On functional components write like below:

import React, { useRef } from 'react';

const App = () => {
  const inputRef = useRef(null);

  return (
    <div ref={inputRef}~~~
  );
};

Definitely, the referenced element is mutable object but it should persist for the full lifetime of the component. it is not my opinion, this words are for ReactJS docs.

like image 31
AmerllicA Avatar answered Oct 05 '22 12:10

AmerllicA