Friday, April 13, 2018

createRef API in React 16.3

Refs allow us to access DOM elements or react elements which belong to a different parent component. The React.createRef API  from React 16.3 provides us a structured way to handle refs instead of the conventional string refs in the previous versions.

The normal way of modifying react elements is to modify the components props/state and trigger render() of the component. React provide us escape hatch to access DOM elements and other parent components elements using refs API. We should make sure that you dont over use ref's in react Applicants and use it only in exceptional cases where the conventional render() option does not work out.

We should create a ref using React.createRef() and attach it to the required element/control using the ref attribute. Once assigned the ref can be accessed throughout the component using this.<refName>.current

The below example uses the new createRef API to set the focus on a textbox when the component loads.

class MyComponent extends React.Component {
  constructor(props) {
    this.myRef = React.createRef();

  render() {
    return <input type="text" ref={this.myRef} />;

  componentDidMount() {

Search Flipkart Products:

No comments: