I\'m having trouble understanding what refs are in React. I understand that it\'s a callback function and you put it in the render function, but beyond that I can\'t understand
Refs are an escape hatch which allows you to get direct access to a DOM element or an instance of a component. In order to use them, you add a ref attribute to your component whose value is a callback function which will receive the underlying DOM element or the mounted instance of the component as its first argument.
class UnControlledForm extends Component {
handleSubmit = () => {
console.log("Input Value: ", this.input.value)
}
render () {
return (
)
}
}
refs can also be used with functional components by leveraging closures in JavaScript.
function CustomForm ({handleSubmit}) {
let inputElement
return (
)
}
("Closures" just being a fancy way of saying referencing a variable that's declared outside the function - in this case, inputElement
- within your function, in this case ref={(input) => inputElement = input}
.)