Skip to content

Instantly share code, notes, and snippets.

@a-type
Created March 12, 2018 14:35
Show Gist options
  • Save a-type/3ddc4969810b8ca9d819ccc0cfea7e10 to your computer and use it in GitHub Desktop.
Save a-type/3ddc4969810b8ca9d819ccc0cfea7e10 to your computer and use it in GitHub Desktop.
Render Props Form State Provider
// @flow
import StateProvider from './SearchStateProvider';
import Container from './Container';
const renderSearchControls = ({ term, isFocused, onChange, onFocus, onBlur }) => (
<Container isSearchFocused={isFocused}>
<input value={term} onChange={onChange} onFocus={onFocus} onBlur={onBlur} />
</Container>
);
export default () => (
<StateProvider>
{renderSearchControls}
</StateProvider>
);
// @flow
import React from 'react';
type SearchStateProviderRenderArgs = SearchState & {
onChange: (term: string) => void,
onFocus: () => void,
onBlur: () => void,
};
type SearchStateProviderProps = {
children: (args: SearchStateProviderRenderArgs) => any,
};
type SearchState = {
term: string,
isFocused: boolean,
};
export default class SearchStateProvider extends React.Component<*, SearchState> {
state = {
term: '',
isFocused: false,
};
handleChange = (term: string) => this.setState({ term });
handleFocus = () => this.setState({ isFocused: true });
handleBlur = () => this.setState({ isFocused: false });
render() {
return this.props.children({
...this.state,
onChange: this.handleChange,
onFocus: this.handleFocus,
onBlur: this.handleBlur,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment