How to implement onChange and value props so that Image uri could be saved outside the component?
Using expo ImagePicker and React Native.
type PhotoComponentProps = {
value: string | undefined;
onChange: (value: string | undefined) => void;
};
export function PhotoComponent({value, onChange} : PhotoComponentProps) {
const [pickedImage, setImage] = React.useState<string | null>(null);
const pickImage = async () => {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: false,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
setImage(result.uri);
}
};
function deleteImage() {
setImage(() => null);
}
return (
<View>
<Button onPress={deleteImage} />
<Button onPress={openCamera} />
<Button onPress={pickImage} />
{pickedImage && <Image source={{ uri: pickedImage }} style={{ width: 200, height: 200 }}/> }
</View>
);
}
2
Answers
Replaced
pickedImage
withvalue
andsetImage
withonChange
And from otside created a state and passed value
You might have to use a client-state solution if you want to raise your state to a upper level or app level.
I would recommend using Jotai looking at your current problem.But if you want a rock solid solution which should be reusable on other occasions as well, then go for something like redux.
Jotai is simple solution and light weight where as redux is much more complicated and involve boilerplate.