skip to Main Content

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


  1. Chosen as BEST ANSWER

    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} />
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search