Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

Expo ImagePicker, DocumentPicker, Typescript example #392

Open
luCAOrx opened this issue Apr 23, 2021 · 0 comments
Open

Expo ImagePicker, DocumentPicker, Typescript example #392

luCAOrx opened this issue Apr 23, 2021 · 0 comments

Comments

@luCAOrx
Copy link

luCAOrx commented Apr 23, 2021

Description of issue

Add examples with other types of inputs react native

Usage example

With Expo ImagePicker:

import React, { useEffect, useRef, useState } from 'react';

import { Image, Text, View } from 'react-native';

import { TouchableOpacity } from 'react-native-gesture-handler';

import * as ImagePicker from 'expo-image-picker';

import { useField } from '@unform/core';

interface ImagePickerInputProps {
  name: string;
};

export default function ImagePickerInput({name}: ImagePickerInputProps) {
  const [image, setImage] = useState<string>('');

  const { fieldName, registerField, error } = useField(name);

  const imagePickerRef = useRef(null);

  async function handleSelectImages() {
    const { status } = await ImagePicker.requestCameraRollPermissionsAsync();

    if (status !== 'granted') {
      alert('Eita precisamos de acesso ás suas fotos...');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      quality: 1,
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
    });

    if (result.cancelled) {
      return;
    }

    const { uri: image } = result;

    setImage(image);
  };
  
  useEffect(() => {
    registerField({
      name: fieldName,
      ref: imagePickerRef.current,
      getValue() {
        return image;
      }
    });
  }, [fieldName, image, registerField]);

  return (
    <>
      {image ? (
        <View>
          <Image 
            source={{ uri: image }}
          />
        </View>
      ) : (
        <View>
          { error && <Text>{error}</Text>}
          <TouchableOpacity 
            ref={imagePickerRef}
            onPress={handleSelectImages}
          >
            <Text>Sua foto</Text>
          </TouchableOpacity>
        </View>
      )}
    </>
  );
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant