createRef
createRef creates a ref object which can contain arbitrary value.
class MyInput extends Component {
inputRef = createRef();
// ...
}Reference
createRef()
Call createRef to declare a ref inside a class component.
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...Parameters
createRef takes no parameters.
Returns
createRef returns an object with a single property:
current: Initially, it’s set to thenull. You can later set it to something else. If you pass the ref object to React as arefattribute to a JSX node, React will set itscurrentproperty.
Caveats
createRefalways returns a different object. It’s equivalent to writing{ current: null }yourself.- In a function component, you probably want
useRefinstead which always returns the same object. const ref = useRef()is equivalent toconst [ref, _] = useState(() => createRef(null)).
Usage
Declaring a ref in a class component
To declare a ref inside a class component, call