Home > database >  Convert ScrollView to FlatList
Convert ScrollView to FlatList

Time:06-10

Good morning everyone, Im starting with React, and i have a question arose regarding an exercise which I have to change from Scrollview to FlatList, could you help me guide me how to make said change? Thanks in advance :)

import React, {useState, useEffect} from 'react';
import {ScrollView, Text, View} from 'react-native';
import axios from 'axios';
import AlbumDetail from './AlbumDetail';


const AlbumList = (props) => {
  const [photoset, setPhotoset] = useState(null);

  useEffect(() => {
    axios
      .get(
        'https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=6e8a597cb502b7b95dbd46a46e25db8d&user_id=137290658@N08&format=json&nojsoncallback=1',
      )
      .then((response) =>
        setPhotoset(response.data.photosets.photoset),
      );
  }, [])

  function renderAlbums() {
    return photoset.map((album) => (
      <AlbumDetail
        navigation={props.navigation}
        key={album.id}
        title={album.title._content}
        albumId={album.id}
      />
    ));
  }

  return(
    (!photoset ?
        <Text>Loading...</Text>
      :
        <View style={{flex: 1}}>
          <ScrollView>{renderAlbums()}</ScrollView>
        </View>
    )
  )
}

export default AlbumList;

CodePudding user response:

Try this:

const AlbumList = (props) => {
  const [photoset, setPhotoset] = useState(null);

  useEffect(() => {
    axios
      .get(
        "https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=6e8a597cb502b7b95dbd46a46e25db8d&user_id=137290658@N08&format=json&nojsoncallback=1"
      )
      .then((response) => setPhotoset(response.data.photosets.photoset));
  }, []);

  const renderAlbums = ({ album }) => {
    return (
      <AlbumDetail
        navigation={props.navigation}
        key={album.id}
        title={album.title._content}
        albumId={album.id}
      />
    );
  };

  return !photoset ? (
    <Text>Loading...</Text>
  ) : (
    <View style={{ flex: 1 }}>
      <FlatList
        data={photoset}
        renderItem={renderAlbums}
        keyExtractor={(item) => item.id}
      />
    </View>
  );
};

export default AlbumList;

  • Related