Last active
November 11, 2018 05:29
-
-
Save pirey/f226ebe52d3e516592361980e8d858db to your computer and use it in GitHub Desktop.
React HOC to handle refs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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