Search code examples
react-nativeexporeact-native-image-pickerexpo-image-picker

How Would I Display Multiple Images In A Horizontal Scrollview/FlatList with Expo Image Picker?


I've figured out how to display one image at a time, but I would love to allow multiple selections that the user can scroll through horizontally. My code is as follows (I haven't added "allowsMultipleSelections" yet due to the error msgs I've been receiving, but I know it would need to be included):

const [image, setImage] = useState(null);

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes:ImagePicker.MediaTypeOptions.All,
      aspect: [1,1],
       quality:1,
    });

    console.log(result);

    if(!result.canceled) {
      setImage(result.assets[0].uri);
    }
  };

  return (
    <View style={styles.container}>
      {image && <Image source = {{uri:image}} style={styles.image}/>}
      <Button title = "Pick From Media Library" onPress={pickImage}></Button>
      <StatusBar style="auto" />
    </View>
  );
}

I've tried wrapping the view in ScrollView and <Flatlist horizontal: {true}> as well as attempting to change the number in the "result.assets" array to a range ( ex: (result.assets[0-4].uri) )


Solution

  • Use this function to choose an image, then save it in an array state called setselectedimage. To list the images, use the flatlist below.

      const pickImage = async () => {
          let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,
          });
        
          if (!result.cancelled) {
            setSelectedImages(prevImages => [...prevImages, result.uri]);
          }
        };
        return (
          <FlatList
            horizontal
            data={selectedImages}
            renderItem={({ item }) => (
              <Image source={{ uri: item }} style={{ width: 200, height: 200, margin: 10 }} />
            )}
            keyExtractor={(item, index) => index.toString()}
          />
        );