I have an image array where I am updating each value when I click on a button in react and pick an image. However the array is constantly rerendering when I only want it to when I pick an image. Here is my code:
const [fileArray, setFileArray] = useState<string[]>(['', '', '', '', '', '']);
function replaceFileState(file: string, index: number) {
let f = [...fileArray];
f[index] = file;
setFileArray(f);
}
return (
<View>
{permissionStatus ?
<Modal style={styles.bottomModalView} isVisible={modalVisible} backdropOpacity={0}
onBackdropPress={() => setModalVisible(false)}>
<View style={styles.modal}>
<TouchableOpacity>
<Text style={{
borderBottomWidth: 1,
borderBottomColor: '#FFF',
color: '#FFF',
textDecorationLine: 'underline',
alignSelf: 'flex-end',
justifyContent: 'center',
paddingTop: 40
}}>All photos</Text>
</TouchableOpacity>
<ScrollView horizontal={true} scrollEnabled={true}
contentContainerStyle={{justifyContent: 'center', alignItems: 'center'}}>
{files.map((file, index) => {
return (
<TouchableWithoutFeedback onPress={() => replaceFileState(file, index)}>
<Image
key={file}
style={{width: 100, height: 100, marginLeft: 10, marginRight: 10, borderRadius: 4}}
source={{uri: file}}
/>
</TouchableWithoutFeedback>
);
})}
</ScrollView>
<Text style={{fontSize: 22, color: '#FFF', marginLeft: 20, marginBottom: 20}}>Your photos</Text>
</View>
</Modal> :
<View/>
}
<Text>Upload your photos</Text>
{fileArray.map((image) => {
return (
image === '' ?
<OnboardingPhoto setStatus={setPermissions} setModal={setIsModalVisible}/>
: <Image
key={image}
style={{width: 100, height: 100, marginLeft: 10, borderRadius: 100}}
source={{uri: image}}
/>
)
})}
</View>
);
It is a modal that has all the users latest images and on click of each image it replaces the empty placeholder image with the users image on the screen. However it constantly rerenders. Id say put it in a useEffect
but I do not know where! Any help would be great, thanks!
CodePudding user response:
I think you need to define a key
property on the TouchableWithoutFeedback
component.
See the guidelines here: https://reactjs.org/docs/lists-and-keys.html
CodePudding user response:
Hooks are ment to be used inside Function Components, that's maybe one of the reasons.