React Native - Navigation + Image

Asked

Viewed 952 times

3

I’m having a hard time solving a problem I’m having using the lib navigation of React.

When I open a post, for example, sending it the image parameter, it returns me the following error message.

inserir a descrição da imagem aqui

My code is this:

render() {
    const {params} = this.props.navigation.state;
    var image = require(images + params.image);
    return (
        <ScrollView style={styles.container}>
            <Image style={styles.cover} source={image}/>
            <Text>{params.title} {image}</Text>
        </ScrollView>
    );
}

Someone who’s been through it can help me, please?

Thanks.

2 answers

2

This is a very common error in React-Native and JS itself. For some reason, require() doesn’t work that way.

You can do as below to popular an array of objects and make a map to popular the ScrollView, take the images of the array objects and then at the time of showing a detail screen you can pass the data of your array.

Example using object array + React-navigation:

render() {
  const dados = [
    {
      imagem: require('./img1.png'),
      titulo: 'Usuario 1',
    },
    {
      imagem: require('./img2.png'),
      titulo: 'Usuario 2',
    },
    {
      imagem: require('./img3.png'),
      titulo: 'Usuario 3',
    },
    {
      imagem: require('./img4.png'),
      titulo: 'Usuario 4',
    },
  ];
  return (
    <ScrollView>
      {dados.map((dados, i) => (
        <View key={i}>
          <Image source={dados.imagem} />
          <Text>{dados.title}</Text>
          <Button onPress={() => this.props.navigation.navigate('telaExemplo', {
            imagem: dados.imagem,
            titulo: dados.titulo
          })} />
        </View>
      ))}
    </ScrollView>
  )
}

0

You can also solve the problem using Template String.

render() {
    const {params} = this.props.navigation.state;
    var image = require(`${params.image}`);
    return (
        <ScrollView style={styles.container}>
            <Image style={styles.cover} source={image}/>
            <Text>{params.title} {image}</Text>
        </ScrollView>
    );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.