Create Ref using React.createRef without using constructor in React?
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:
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();
}