diff --git a/README.md b/README.md index 0414829..640a5fc 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_601 TILs and counting..._ +_602 TILs and counting..._ --- @@ -430,6 +430,7 @@ _601 TILs and counting..._ - [Proxy To An API Server In Development With CRA](react/proxy-to-an-api-server-in-development-with-cra.md) - [Quickly Search For A Component With React DevTools](react/quickly-search-for-a-component-with-react-devtools.md) - [Rendering Multiple Nodes With Fragments](react/rendering-multiple-nodes-with-fragments.md) +- [Use A Ref To Autofocus An Input](react/use-a-ref-to-autofocus-an-input.md) ### Ruby diff --git a/react/use-a-ref-to-autofocus-an-input.md b/react/use-a-ref-to-autofocus-an-input.md new file mode 100644 index 0000000..1b24045 --- /dev/null +++ b/react/use-a-ref-to-autofocus-an-input.md @@ -0,0 +1,39 @@ +# Use A Ref To Autofocus An Input + +When creating highly interactive interfaces with React, we are trying to +make the user's experience of our app as smooth as possible. This means that +when an edit button reveals an input field, we want that field to be in +focus so that the user can immediately start typing. + +This is a great use for React's `ref` prop. When you supply your component +with a function as the `ref` prop, that function will be called with a +reference to itself on mount and with `null` on unmount. + +```javascript +class MyAutofocusInput extends React.Component { + focusInput = (component) => { + if (component) { + component.focus(); + } + } + + render() { + return ( + + ) + } +} +``` + +When this component gets rendered, the input will be focused via our +`focusInput` function. + +Note: refs only work with class component, so don't try to use it on a +functional component. + +See [Refs and the DOM](https://reactjs.org/docs/refs-and-the-dom.html) in +React's documentation for more details.