react ref methods code example
Example 1: react.createref()
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef(); this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus(); }
render() {
// tell React that we want to associate the ref
// with the `textInput` that we created in the constructor
return (
);
}
}
Example 2: when to use react ref
WHEN TO USE REACT'S REF ATTRIBUTE?
But it is not always a good idea to use the ref attribute. The general rule of thumb is to avoid it. The official React documentation mentions three occasions where you can use it because you have no other choice.
Managing focus, text selection, or media playback.
Integrating with third-party DOM libraries.
Triggering imperative animations.
Example 3: refs react js
class Lesson9Refs extends Component {
onAddProduct = () => {
alert(this.refs.productname.value);
}
return (
Featured
{ elements }
);
}
}
export default Lesson9Refs;
Example 4: cre&atRefs react js
const node = this.myRef.current;