reactjsreact-nativeexpoimagepicker

save Image uri outside of its component - React Native


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

}


Solution

  • Replaced pickedImage with value and setImage with onChange

      type PhotoComponentProps = {
        value: string | undefined;
        onChange: (value: string | undefined) => void;
    };
    
    export function PhotoComponent({value, onChange} : PhotoComponentProps) {
    
    const pickImage = async () => {
        const result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: false,
            aspect: [4, 3],
            quality: 1,
        });
    
        if (!result.cancelled) {
            onChange(result.uri);
        }
    };
      
    return (
                <View>
                    <Button onPress={openCamera} />
                    <Button onPress={pickImage} />
                   {value && <Image source={{ uri: value }} style={{ width: 200, height: 200 }}/> }
                </View>
    );
    

    And from otside created a state and passed value

    const [value, setValue] = React.useState<string | undefined>(undefined);
    
    <Photo onChange={setValue} value={value} />