Skip to content

Instantly share code, notes, and snippets.

@nurpax
Last active April 13, 2018 08:52
Show Gist options
  • Save nurpax/61bb75698c2b2a74b23462148cc73848 to your computer and use it in GitHub Desktop.
Save nurpax/61bb75698c2b2a74b23462148cc73848 to your computer and use it in GitHub Desktop.
// "container" for Kcal input forms (sets up formik with validation for the kcal fields).
export const KcalForm = ({ initialValues, onSubmit, render }) => {
return (
<Formik
initialValues={initialValues}
validateOnChange
validate={values => {
let errors = {}
if (values.amount === '') {
errors.amount = '# of kcals required'
}
// validate number
return errors
}}
onSubmit={(values, { resetForm }) => {
resetForm()
onSubmit({
...values,
foodId: null,
recipeId: null
})
}}
render={render}
/>
)
}
export const FloatField = ({ name, className, ...rest }) => (
<Field
{...rest}
name={name}
className={classNames('input', className)}
type='number'
step={0.01}
/>
)
export const TextField = ({ name, className, ...rest }) => (
<Field
{...rest}
name={name}
className={classNames('input', className)}
type='text'
/>
)
// A row of input fields, vertically aligned
// Optionally with buttons aligned on the right
export class HorizontalFormInputs extends Component {
static propTypes = {
inputs: PropTypes.object.isRequired,
buttons: PropTypes.object
}
render () {
return (
<div style={{display: 'flex', alignItems:'space-between'}}>
<div style={{display: 'flex', alignItems:'center'}}>
{this.props.inputs}
</div>
{this.props.buttons ?
<div style={{display: 'flex', alignItems:'center'}}>
{this.props.buttons}
</div>
: null
}
</div>
)
}
}
const KcalInput = ({ onSubmit }) => {
return (
<KcalForm
onSubmit={onSubmit}
initialValues={{
quickDesc: '',
amount: ''
}}
render={({touched, errors, isValid}) => {
return (
<Form autoComplete='off'>
<label className='label' >Quick add calories:</label>
<HorizontalFormInputs
inputs={
<Fragment>
<TextField name='quickDesc'
style={{ width: '50%', marginRight: '0.5rem' }}
placeholder='Description..' />
<FloatField name='amount'
style={{ width: '25%', marginRight: '0.5rem' }}
className={classNames(touched.amount && errors.amount ? 'is-danger' : null)}
placeholder='Kcals..' />
</Fragment>
}
buttons={
<button type='submit'
style={{width: '100%'}}
disabled={!isValid}
className='button is-primary'>Add
</button>
}
/>
</Form>
)
}}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment