velvetytoast
velvetytoast

Reputation: 45

React - loading static images into a flat list

I'm new to react and I'm writing an application that loads images from the local file system into a flat list to provide an image picker. I'm loading the images into an array in the component did mount method and adding this as a datasource to the state so that the render gets triggered when the image have been loaded.

I've tried the require keyword and this gives a syntax error, I've also tried to load the images as uri but this renders a blank layout.

Gives me a syntax error at column 53 of the first image load - the open bracket of the require

componentDidMount() {
    var that = this;
    let items: [{"key": "r", "image": require("./img/image1.jpg")},
                {"key": "b", "image": require("./img/image2.jpg")},
                {"key": "j", "image": require("./img/image3.jpg")}
                ];
    that.setState({
        dataSource: items,
    });
 }

in the flat list I'm using

<View style={{ flex: 1, flexDirection: 'column', margin: 1 }}>
                            <Image style={styles.imageThumbnail} source={{item.image} />
                        </View>

and the error I'm getting is

SyntaxError: /Users/xxxxxxx/react-native/simpleproject/screens/HomeScreen.js: Unexpected token (23:49)

  21 |     componentDidMount() {
  22 |         var that = this;
> 23 |         let items: [{"key": "r", "image": require("./img/image1.jpg")},
     |                                                  ^
  24 |                     {"key": "b", "image": require("./img/image2.jpg")},
  25 |                     {"key": "j", "image": require("./img/image3.jpg")}
  26 |                     ];

As far as I can see this is the correct syntax.

Upvotes: 0

Views: 1672

Answers (2)

Junius L
Junius L

Reputation: 16122

You are using : to initialize your items.

initialize items like

let items = [{"key": "r", "image": require("./img/image1.jpg")},
   {"key": "b", "image": require("./img/image2.jpg")},
   {"key": "j", "image": require("./img/image3.jpg")}
 ];

Demo

Upvotes: 1

Afsanefda
Afsanefda

Reputation: 3339

You probably need a nodejs server so that you can use the file protocol on your system on your react application. Take a look at this answer.

Upvotes: 0

Related Questions