Steven L.
Steven L.

Reputation: 2155

Displaying Images in ListView for React Native

I have two presentational components. The first, called Category simply renders a React Native ListView component after doing a bit of set-up work.

The second component, Book, simply displays the data as text, with an image that should be fetched through the network.

Unfortunately, the Image doesn't seem to be displaying at all. Can someone help me get the image to display? Below, please find the Category and Book component definition, as well as a sample of the props being past to Book.

Category.js

import React from 'react';
import { ListView, Text } from 'react-native';
import _ from 'lodash';
import { camelizeKeys } from 'humps';

import Book from './Book';

const Category = ({ category }) => {
  let element;

  if (!_.isEmpty(category)) { // if data is available
    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    const camelCasedBooks = camelizeKeys(category.results.books);
    const data = ds.cloneWithRows(camelCasedBooks);

    element = (
      <ListView
        dataSource={data}
        enableEmptySections
        renderRow={(book) => <Book {...book} />}
      />
    );
  } else { // if data is not available
    element = (
      <Text>Loading</Text>
    );
  }

  return element;
};

Category.propTypes = {
  category: React.PropTypes.object.isRequired,
};

export default Category;

Book.js

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

const Book = ({ author, bookImage, description, title }) =>
  <View>
    <Text>
      {author}
    </Text>
    <Text>
      {bookImage}
    </Text>
    <Text>
      {description}
    </Text>
    <Text>
      {title}
    </Text>
    <Image source={{ uri: bookImage }} />
  </View>;

Book.propTypes = {
  author: React.PropTypes.string.isRequired,
  bookImage: React.PropTypes.string.isRequired,
  description: React.PropTypes.string.isRequired,
  title: React.PropTypes.string.isRequired,
};

export default Book;

Sample Book Props

{
 author: "Vi Keeland",
 bookImage: "https://s1.nyt.com/du/books/images/9781942215462.jpg",
 description: "Reese dismisses a chance encounter with a smug stranger, until he turns out to be her new boss.",
 title: "BOSSMAN"
}

Upvotes: 1

Views: 5656

Answers (1)

Thomas
Thomas

Reputation: 8003

When using images that come from a remote location (such as your bookImage you need to set an explicit width and height on the Image's style. This is due to the fact that there is not automatic way for react-native to know how big the images is going to be.

Check the Image documentation for strategies on calculating the Image's size before being rendered. In my experience however simply setting the width and height explicitely is enough most of the times.

Upvotes: 3

Related Questions