Showing posts with label createRef API. Show all posts
Showing posts with label createRef API. Show all posts

Thursday, August 9, 2018

createRef API example in React

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 this example we shall see on how createRef API can be used to get the value entered in a textbox control. The ref "myCreateRef" is used to get the value from the textbox and set it to the state. From React 16.3 onwards the new createRef API should be used instead of the string refs, though string refs are still supported it is recommended to use createRef API going forward. The string ref will eventually get deprecated.

Wednesday, August 1, 2018

What's new in React 16.3

React 16.3 introduces the following new features
  1. Context API
  2. createRef API
  3. ref Forwarding
  4. new Component Lifecycle Changes
  5. StrictMode
Let us now look into these features in detail.

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.