mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Use A Ref To Autofocus An Input as a react til
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
39
react/use-a-ref-to-autofocus-an-input.md
Normal file
39
react/use-a-ref-to-autofocus-an-input.md
Normal file
@@ -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 (
|
||||
<input
|
||||
ref={this.focusInput}
|
||||
value={this.props.value}
|
||||
onChange={this.props.onChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
Reference in New Issue
Block a user