React.js
Angular
Ethical Hacking
Agile
AWS
BlockChain
Cassandra
Cloud
Salesforce
Scaled Agile
TOGAF
DevOps
GIT
Jenkins
Jira
Kibana
Linux
NGINX
Ansible
Artificial Intelligence
in React JS by

How to create refs?

Click here to read more about React JS

1 Answer

0 votes
by

There are two approaches

  1. This is a recently added approach. Refs are created using React.createRef() method and attached to React elements via the ref attribute. In order to use refs throughout the component, just assign the ref to the instance property within 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 ref callbacks approach regardless of React version. For example, the search bar component's input element 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 using closuresNote: You can also use inline ref callbacks even though it is not a recommended approach

Related questions

Madanswer
0 votes
0 votes
asked Jun 19 in React JS by JackTerrance
0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
...