Skip to content

Instantly share code, notes, and snippets.

@jaredpalmer
Created September 5, 2018 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredpalmer/bf380a214dfa4141e0bb3f8a090d6ac2 to your computer and use it in GitHub Desktop.
Save jaredpalmer/bf380a214dfa4141e0bb3f8a090d6ac2 to your computer and use it in GitHub Desktop.
Fieldset
import React from 'react';
import { Field, connect } from 'formik';
import {
FormLabel,
FormGroup,
FormFeedback,
FormHelper,
} from 'common/components/Form';
import { FirstMatchingNodeTarget } from 'common/components/Form/FirstMatchingNodeTarget';
import scrollIntoView from 'smooth-scroll-into-view-if-needed';
class FieldsetImpl extends React.Component<any, {}> {
// control: any = null; // ref to the field control
control = React.createRef<HTMLInputElement>();
render() {
const {
name,
id,
label,
wrapperClassName,
helpText,
helpRender,
beforeField,
small,
flex,
...props
} = this.props;
const key = id || name;
const { errors, touched, values } = this.props.formik;
const hasError = !!errors[key] && !!touched[key];
return (
<FirstMatchingNodeTarget
id={key}
onMatch={node => {
scrollIntoView(node, {
scrollMode: 'if-needed',
block: 'center',
inline: 'center',
}).then(() => {
if (this.control.current) {
this.control.current.focus();
}
});
}}
>
{scrollTargetProps =>
flex ? (
<FormGroup
{...scrollTargetProps}
className={wrapperClassName || 'xs-mb2'}
invalid={hasError}
>
<div className="clearfix gutters">
<div className="col xs-col-12 md-col-3 ">
<div className="xs-col-12 md-text-right">
<FormLabel htmlFor={key} small={small}>
{label}
</FormLabel>
</div>
</div>
<div className="col xs-col-12 md-col-9">
{beforeField && beforeField({ errors, touched, values })}
<Field
innerRef={this.control as any}
id={key}
name={key}
{...props}
/>
{hasError && <FormFeedback>{errors[key]}</FormFeedback>}
{helpText && <FormHelper>{helpText}</FormHelper>}
{helpRender && helpRender()}
</div>
</div>
</FormGroup>
) : (
<FormGroup
{...scrollTargetProps}
className={wrapperClassName || 'xs-mb2'}
invalid={hasError}
>
<FormLabel htmlFor={key} small={small}>
{label}
</FormLabel>
{beforeField && beforeField({ errors, touched, values })}
<Field
innerRef={this.control as any}
id={key}
name={key}
{...props}
/>
{hasError && <FormFeedback>{errors[key]}</FormFeedback>}
{helpText && <FormHelper>{helpText}</FormHelper>}
{helpRender && helpRender()}
</FormGroup>
)
}
</FirstMatchingNodeTarget>
);
}
}
export const Fieldset = connect(FieldsetImpl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment