Skip to content

Instantly share code, notes, and snippets.

@pirey
Last active November 11, 2018 05:29
Show Gist options
  • Save pirey/f226ebe52d3e516592361980e8d858db to your computer and use it in GitHub Desktop.
Save pirey/f226ebe52d3e516592361980e8d858db to your computer and use it in GitHub Desktop.
React HOC to handle refs
import { withStateHandlers } from 'recompose'
import { ReactNode } from 'react';
type Ref = ReactNode
type RefsState = {}
type RefsHandlers = {
setRef: (fieldName: string, ref: Ref) => undefined
focusRef: (fieldName: string) => undefined
}
export type RefsProps = RefsHandlers & RefsState
export const createRefHandlers = () => {
const refs = {}
// we use closure so that `refs` object does not clash with other hoc users
const withRefs = withStateHandlers<RefsState, RefsHandlers>(
{},
{
setRef: state => (fieldName, ref) => {
refs[fieldName] = ref
return undefined
},
focusRef: state => fieldName => {
if (refs[fieldName]) {
refs[fieldName].focus()
}
return undefined
}
}
)
return withRefs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment