Refs is a handle to a DOM element or component instance that React provides us with secure access. We can add the ref attribute to the element and then accept the element’s handle to the DOM tree in the callback function, which is returned as the first argument to the callback function:

class CustomForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}
Copy the code

The input field in the code above contains a ref attribute that declares a callback function that accepts the DOM element corresponding to the input, which we bind to the this pointer for use in other class functions. It is also worth noting that refs are not exclusive to class components. Functional components can also use closures to temporarily store their values:

function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
        type='text'
        ref={(input) => inputElement = input} />
      <button type='submit'>Submit</button>
    </form>
  )
}
Copy the code

Source link: segmentfault.com/a/119000001…