Render a list of data

πŸ“‘ What you will learn

  • Add a performant Scroll for long lists with <FlatList>

πŸ‘Ύ Before we start the exercise

Implicit return vs. normal return

In JavaScript, there are two ways to write a function that returns a value:

// βœ… function with implicit return
const Item = ({ title }) => (
  <View>
    <Text>{title}</Text>
  </View>
);

The function Item uses an implicit return β€”with ( ... ), which is a shorter syntax suitable for single-expression functions.

// βœ… function normal return
const ItemWithReturn = ({ name }) => {
  return (
    <View>
      <Text>{name}</Text>
    </View>
  );
};

The second function ItemWithReturn uses a normal return, which allows for more complex function bodies and explicit handling of the return value. It also gives the ability to include additional logic before returning the JSX elements.

πŸ‘¨β€πŸš€ Exercise 4

Create a new GitHub repository

Repository name: spacecraft

Description: A React Native application build with expo. Created during my bootcamp https://davidl.fr/bootcamp

  • ❗ Commit your work if it's not already done.
  • Push your code to GitHub.

Download dummy data on you computer

⚠️ For Windows users, copy this file and paste it to api/data.json.

  • Run a curl from your terminal to download dummy data on your computer.
mkdir api
curl https://swapi.py4e.com/api/starships/ > api/data.json

Convert JavaScript value to a JSON string

We will use JSON.stringify() here to render a string version of the data.

  • Create a new file ./src/screens/StarshipFeedScreen.tsx and paste the content from this StarshipFeedScreen
  • Uncomment the lines and to display the array results from data

Here is a preview of what you should have:

a preview of a React Native app with raw data

Render a list of data with FlatList

Implement a FlatList for the data that is fetched.

  • Read the FlatList documentation.
  • Add your array to the props data.
  • Render Item with name, model, crew, hyperdrive_rating and cost_in_credits (Notice on the documentation we use an implicit return).
  • If you want to add an Image just use this api to generate random images https://picsum.photos/seed/car/400/200, you can change car with something else to generate a new image.

πŸ‘½ Bonus