Skip to content Skip to sidebar Skip to footer

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);

Solution 1:

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

classAppextendsReact.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();
  }

Solution 2:

Yes, you can. For example:

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

  return (
    <inputref={inputRef} />
  );
}

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

render() {
  // This won't work.return<MyFunctionalComponentref={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:

Solution 3:

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

Solution 4:

On class components write like below:

importReact, { Component, createRef } from'react';

classAppextendsComponent {
  inputRef = createRef();

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

On functional components write like below:

importReact, { useRef } from'react';

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

  return (
    <divref={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.

Solution 5:

Yes. Exactly as you did with the state (with Babel's class-field support):

classAppextendsReact.Component {
    inputRef = React.createRef();
}

Post a Comment for "Create Ref Using React.createref Without Using Constructor In React?"