How do you create refs? in REACT

Practice



There are two approaches

  1. This is a recently added approach. Refs are created using the
    React.createRef()
    method and attached to React elements via the
    ref
    attribute. To use refs throughout the component, simply assign the ref to an instance property in the constructor.
class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
  }
  render() {
    return <div ref={this.myRef} />
  }
}
  1. You can also use the ref callbacks approach regardless of the React version. For example, the input element of a search bar component is accessed as follows:
class SearchBar extends Component {
   constructor(props) {
      super(props);
      this.txtSearch = null;
      this.state = { term: '' };
      this.setInputSearchRef = e => {
         this.txtSearch = e;
      }
   }
   onInputChange(event) {
      this.setState({ term: this.txtSearch.value });
   }
   render() {
      return (
         <input
            value={this.state.term}
            onChange={this.onInputChange.bind(this)}
            ref={this.setInputSearchRef} />
      );
   }
}

You can also use refs in function components by using closures . Note . You can also use inline ref callbacks, even though this is not the recommended approach.

created: 2020-02-23
updated: 2026-03-08
208



Was this answer useful?
Choose a quick rating so we can improve the next answer for you.
How satisfied are you?


Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Scripting client side JavaScript, jqvery, BackBone"

Terms: Scripting client side JavaScript, jqvery, BackBone