Yellow Clock
Yellow Clock

Reputation: 465

React Native : How to add multiple functions for onChangeText using Formik

I try to make a simple TextInput that limits the number of words the user can enter by using Formik .

enter image description here

However ,I got stuck here .. I had used useSate hook for counting the length of enter value ,which needs to put into the onChangeText callback of TextInput . In the meanwhile ,I need to put the handleChange(name) for submitting the content in the onChangeText also .. And I realize ,only one of them can work with the code below ... I have no idea what is going on...Could you please take a look of my code ? Thank you so much in advance !!

import { StyleSheet, Text, View,TextInput} from 'react-native'
import React,{useState} from 'react'
import { useFormikContext } from 'formik';


const AppFormFieldWithCount = ({name,number,maxLength,minHeigh,multiline,placeholder,...otherProps}) => {
    const {setFieldTouched,handleChange,errors,touched} = useFormikContext();
    const[content,setContent] = useState('');
  
  return (
   <>
    <View style={[styles.container,{height:minHeigh}]}>
   <TextInput placeholder={placeholder}
     style={{flex:1,fontSize:16}} 
     placeholder = {placeholder}
     multiline={multiline} 
     maxLength={maxLength}
     minHeigh ={minHeigh}
     onBlur = {()=>setFieldTouched(name)}
     onChangeText = { 
      (text) => {setContent(text);handleChange(name)}
     
    }
     {...otherProps}
      />
     <Text style={{position:'absolute',bottom:5,right:5,}}>{content === "" ? "0" : content.length}/{number}</Text>
     </View>

   </>
  )
}

export default AppFormFieldWithCount

const styles = StyleSheet.create({
  container:{
    flexDirection:'row',
    borderRadius:5,
    borderWidth:1,
    borderColor:"black",
    width:'100%',
    paddingHorizontal:10,
    marginVertical:10,

}
})

Upvotes: 1

Views: 947

Answers (1)

aribambang
aribambang

Reputation: 56

you can use setFieldValue from useFormikContext

onChangeText = { 
  (text) => {
    setContent(text);
    setFieldValue('name', text)}
}

Upvotes: 3

Related Questions