iLightFPS
iLightFPS

Reputation: 63

How do i make so the TextInput clears after submit in react native

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>
 );
}

Upvotes: 0

Views: 34

Answers (1)

Muhammad Mehar
Muhammad Mehar

Reputation: 1055

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.

Upvotes: 1

Related Questions