Created
May 23, 2020 02:15
-
-
Save benedictjohannes/5a6e41c714c9a65ab86a9f6bd8f98aaf to your computer and use it in GitHub Desktop.
An opinionated implementation of Ionic input handling for @ionic/react with Formik
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 React from 'react' | |
import { IonInput, IonItem, IonLabel } from '@ionic/react' | |
//SCSS | |
// .validationMessage { | |
// display: none; | |
// &.error { | |
// display: block; | |
// font-size: 0.8rem; | |
// color: #ff3333; | |
// } | |
// } | |
const defaultLabelProps = { position: 'floating' } | |
const defaultInputProps = {} | |
const IonicInput = ({ | |
labelText, | |
labelProps = {}, | |
inputProps = {}, | |
type, | |
name, | |
values, | |
touched, | |
errors, | |
setFieldValue, | |
setFieldTouched, | |
}) => { | |
const blurHandler = (e) => { | |
setFieldValue(name, e.target.value) | |
setFieldTouched(name) | |
} | |
const focusHandler = e => { | |
setFieldTouched(name) | |
} | |
const changeHandler = e => { | |
const usedValue = type!=='password' && e.target && e.target.value ? e.target.value : e.detail.value | |
setFieldValue(name, usedValue) | |
setFieldTouched(name) | |
} | |
const inputHandler = e => { | |
setFieldValue(name, e.target.value) | |
} | |
return ( | |
<div> | |
<IonItem className={errors && errors.email && touched.email ? 'ion-invalid' : ''}> | |
<IonLabel {...{ ...defaultLabelProps, ...labelProps }}>{labelText}</IonLabel> | |
<IonInput | |
type={type} | |
name={name} | |
value={values[name]} | |
onIonBlur={blurHandler} | |
onIonChange={changeHandler} | |
onIonFocus={focusHandler} | |
onIonInput={inputHandler} | |
{...{ ...defaultInputProps, ...inputProps }} | |
/> | |
</IonItem> | |
<div className={`validationMessage ${errors && errors[name] && touched[name] ? 'error' : ''}`}> | |
{errors[name]} | |
</div> | |
</div> | |
) | |
} | |
export default IonicInput | |
// USAGE | |
// <IonicInput | |
// name='pass' | |
// type='password' | |
// label='Your Password' | |
// { ...formikProps} | |
// /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment