Before we talk about uncontrolled components, let’s understand the concept of Refs and the DOM.

Refs and DOM

In a typical React data flow, props is the only way parent-child components interact. To modify the child component, re-render the child component by modifying the props. The Refs attribute, on the other hand, provides a way to force changes to child components outside of the typical data flow. The child component being modified may be a DOM element or a React instance of the component.

Use the refs attribute

Create a ref with the React.createref () function and attach it to the React element via the ref attribute:

class MyComponent extends React.Component { constructor(){ super(); this.myRef = React.createRef(); this.handleClick = this.handleClick.bind(this); } handleClick(){ console.log(this.myRef.current) } render(){ return <button ref={this.myRef} OnClick ={this.handleClick}> </button>}}Copy the code

When a ref is passed to an element in render, a reference to that node can be accessed in the ref’s current property.

const node = this.myRef.current
Copy the code

If the ref attribute belongs to an HTML element, the underlying DOM element is accepted as the current attribute.

If the REF attribute belongs to a class component, the REF object receives the component’s mounted instance as its current attribute.

The React component passes a DOM element to the current property when mounted and a NULL value when unmounted. The ref is updated before the componentDidMount or componentDidUpdate lifecycle hook is triggered.

Refs forward

You cannot use ref on a function component because it has no instance. But it can be used inside functional components (using the useRef hook) as long as it points to a DOM or class component instance. To use the ref attribute in a functional component, use forward ref:

const FancyButton = React.forwardRef((prop, refProp) => {
  return <button ref={refProp}></button>
})
const refForward = React.createRef();
<FancyButton ref={refForward}></FancyButton>
Copy the code

This gives access to the button element through ref, and the FancyButton receives the REF and passes it down to the child component, called ref forwarding.

Refs callback

The ref callback allows access to the child component from the parent component. By passing a function to the ref attribute:

function CustomTextInput(props) { return ( <div> <input ref={props.inputRef} /></div> ); } class Parent extends React.Component { render() { return ( <CustomTextInput inputRef={el => this.inputElement = el} /> ); }}Copy the code

In this example, we pass the callback attribute from the parent to the child, which sets the ref attribute to the callback function, so that the parent’s inputElement points to the child’s input element.

References:

React