Home > Enterprise >  save Image uri outside of its component - React Native
save Image uri outside of its component - React Native

Time:10-31

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

}

CodePudding user response:

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.

CodePudding user response:

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={deleteImage} />
                <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} />
  • Related