Wk-notes-01-30-React-ref

About react reference andReact.forwardRef()

Three ways

I. New hook way,

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

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

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

Last updated