0

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.

2 Answers2

1

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

Junius L
  • 15,881
  • 6
  • 52
  • 96
0

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.

Afsanefda
  • 3,069
  • 6
  • 36
  • 76
  • Thanks - the files already exist in the project in the image folder so I'm assuming they will be bundled into the application because I'm using the require keyword - do I always need to download them from a uri? – velvetytoast May 19 '19 at 12:37
  • you should use `=` not `:` for initializing `items` – arjun May 19 '19 at 13:12
  • The sentence is misleading :) the way you defined the variable is wrong ! misleading = > " from the local file system" – Afsanefda May 19 '19 at 16:35