I have a TextInput
and I don’t want it to re render every time I change the value inside it
JavaScript
x
7
1
const [WrittenVal,setWrittenVal] = useState(()=>'');
2
3
<TextInput
4
value={String(WrittenVal)}
5
onChangeText={text => setWrittenVal(text)}
6
/>
7
but I want to be able to change the value inside the input at the push of a button that’s why I haven’t just used defaultValue
any solutions??
Advertisement
Answer
You can use useRef to save text from text input without render , and useState to show text in input on button press:
Live example : https://snack.expo.dev/TW-fMx1-2
JavaScript
1
43
43
1
import React from "react";
2
import { SafeAreaView, StyleSheet, TextInput,TouchableOpacity,Text } from "react-native";
3
4
const UselessTextInput = () => {
5
const [text, onChangeText] = React.useState("");
6
7
const textRef = React.useRef('')
8
9
const textToRef = (text) =>{
10
textRef.current = textRef.current + text
11
}
12
13
const showTextInInput = () =>{
14
onChangeText( textRef.current )
15
}
16
17
console.log("render")
18
return (
19
<SafeAreaView>
20
<TextInput
21
style={styles.input}
22
onChangeText={textToRef}
23
value={text}
24
/>
25
<TouchableOpacity onPress={showTextInInput}>
26
<Text>SHOW TEXT IN INPUT</Text>
27
</TouchableOpacity>
28
</SafeAreaView>
29
);
30
};
31
32
const styles = StyleSheet.create({
33
input: {
34
height: 40,
35
margin: 12,
36
borderWidth: 1,
37
marginTop:50,
38
padding: 10,
39
},
40
});
41
42
export default UselessTextInput;
43