Reputation: 916
I'm working on an app which the users will enter large number of records continuously. Currently, I'm using State
to clearing the input when submit is pressed. So by considering performance issues i'd like to clear the input using ref
property. So i've tried by using these.
1- firstref.current.clear();
2- firstref.current.setNativeProps({ text: '' });
3- firstref.current.value = '';
But the input field is not clearing the value after submit. I'm using a custom input component. Here is a demo by clearing the input using state. Demo using state
<View style={styles.fixedform}>
<View style={styles.textinputViewleft}>
<TextInput
style={styles.textinput}
ref={firstref}
label="Digit"
returnKeyType="next"
value={digit.value}
onChangeText={(text) => { setDigit({ value: text, error: '' }); if (text.length === 3) { ref.current.focus(); } }}
error={!!digit.error}
errorText={digit.error}
keyboardType="numeric"
maxLength={3}
minLength={3}/>
</View>
<View style={styles.textinputView}>
<TextInput
style={styles.textinput}
ref={ref}
label="Count"
value={count.value}
onChangeText={(text) => setCount({ value: text, error: '' })}
error={!!count.error}
errorText={count.error}
keyboardType="numeric"
maxLength={3}/>
</View>
<View style={styles.textinputView}>
<Button loading={loading} disabled={disabled} style={styles.buttonView} mode="contained" onPress={onSubmitPress}>Submit</Button>
</View>
</View>
Upvotes: 0
Views: 2483
Reputation: 1496
looks like this is a bug in TextInput of react-native-paper package.
also this line:
scrollViewRef.current.scrollToEnd({animated: true})
is giving me an error:
Cannot read property 'scrollToEnd' of undefined.
I commented this like to see what is happening with refs.
First of all, you cannot get the value of TextInput with ref (not yet).
I continue changing the code and i noticed that
digitRef.current.focus();
this line is focusing and also giving TextInput the previous text!
you can see that by adding setTimeout between focus and clear to see what's happening.
workaround is using TextInput of 'react-native' instead of 'react-native-paper'.
here is a working code:
https://snack.expo.io/@arminya/demoprjct
Upvotes: 1
Reputation: 2987
What you looking for is to make react rerender after changing ref which is imposible.
If you want to trigger a re-render after the ref changes, you must use useState instead of useRef. Only that way can you ensure that the component will re-render.
As stated in React document
Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.
Upvotes: 0
Reputation: 1549
Instead of using "React.useRef" you should use "React.createRef".
const firstref = React.createRef(null);
Then
firstref.current.clear();
will work
Upvotes: 0