0

I have a TextInput in my code that doesn't clear itself after submit and i have no idea on why it does that or how to solve it. I've looked at other posts that has this kinda issue? but none works or i don't really know where to place the code to make it clear itself after submiting.

Code

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


export default function AddList({ submitHandler }) {

const [text, setText] = useState('');

const changeHandler = (val) => {
    setText(val);
}
return(
    <View style={styles.container}>
        <View style={styles.wrapper}>
            <TextInput 
                style={styles.input}
                placeholder='text'
                onChangeText={changeHandler}
            />
            <Button onPress={() => submitHandler(text)} title='ADD' color='#333' />    
        </View>  
    </View>
 );
}
iLightFPS
  • 63
  • 1
  • 8

1 Answers1

1

Simply create a new function after useState as below:

const onSubmit = useCallback(() => {
   if (submitHandler) submitHandler(text)
   setText("")
}, [text])

and modify textinput and button as below:

   <TextInput
       style={styles.input}
       placeholder='What Tododay?'
       onChangeText={changeHandler}
       value={text}
   />
   <Button
       onPress={onSubmit}
       title='ADD TO LIST'
       color='#333'
    /> 

Do not forget to import useCallback from react.

I hope it help you.

Muhammad Mehar
  • 1,015
  • 7
  • 10