> For the complete documentation index, see [llms.txt](https://notes.lirenxn.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://notes.lirenxn.com/2020/wk-notes-01-30-react-ref.md).

# Wk-notes-01-30-React-ref

### About react reference and`React.forwardRef()`

**Three ways**

**I.** New hook way,

**----->** `this.inputRef.current` to get access to the ref

```javascript
const inputEl = useRef(); 
​
// Access it
const onClick = () => inputEl.current.focus();
​
// and pass it to ref props 
return <input ref={inputRef}/ onClick={onClick}>
```

**II. callback ref**, which is triggered whenever refs changed, gives the `el` itelf

**----->**`this.inputRef` to get access to the ref

**In class**

```javascript
class {
  constructor(props){
    this.textInput = null;
​
    this.setTextInputRef = element => {
       // So that you can do crazy things inside
       this.textInput = element;
    };   
  }
  
  render(){
    return <input ref={this.setTextInputRef}/>
  }
}
```

Refs are guaranteed to be up-to-date before `componentDidMount` or `componentDidUpdate` fires.

**III.** Class component way ( >= v16.3 ), use `this.inputRef = React.createRef();` in **constructor(props)** , and pass it into **ref** `ref={this.inputRef}`,

**----->** `this.inputRef.current` to get access to the ref

### **forwardRef()**

**ref** and **key** are not props, they coule not be got from this.props, to forward a **ref**

```
const WrapperButton = React.forwardRef(function(props, ref){
  return <button ref={ref} className="FancyButton">
    {props.children}
  </button>
});
```

The hook to bind handler of **forwarded ref** to current function. Rare.

**useImperativeHandle**

If there is no **DOMNode** to the component/element, the ref will be set as the Component reference itself, which no one really use and care about.

**Caveat:** you need to manually do thing for **HOC** and forwarded the ref

> The second `ref` argument only exists when you define a component with `React.forwardRef` call. Regular function or class components don’t receive the `ref` argument, and ref is not available in props either.

**ref** for `WrapperButton` will be the same as **ref** for `button`
