1

I am working with React Native and trying to get an image to show up based off title variable that is different for a list. I do not think I am handling the strings right with the JavaScript but not sure how to fix this. Any suggestions? It runs fine when I just hardcode the image source path so I know that is correct.

<View style={{ flex: 8 }}>
     this.setState({
         link: './assets/' + this.props.title + '.jpg',
     });
     <Image source={require(this.state.link)} style={[styles.images]} />
</View>
2

3 Answers 3

1

You can't even setState inside a view like that, and for require statement that you can't put a string with concatenating with another set string, always require statement should be completely hard-coded like this require("./assets/image.png"); and the soln can be like this:

import {...} from '...';
    const titleImages = {
      title1: require("./assets/title1.png"),
      title2: require("./assets/title2.png") //here title1/title2 should be the value that you receive in props
    };
    class Anyclass extends Component {
      render() {
        const { title } = this.props;
        return (
          <View style={{ flex: 8 }}>
            <Image source={titleImages[title]} style={[styles.images]} />
          </View>
        );
      }
    }

if you have multiple titles, you can just declare the require statement in titleImages object and can render the image.

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe, could you try to use:

this.setState({ link: `./assets/${this.props.title}.jpg` });

Comments

0

Setting aside the call to setState from inside the render, which should probably be avoided, I think the issue here is that you're trying to use a variable inside a call to require. require calls are resolved at build time by the packager, so they need a static resource (one that doesn't depend on the value of a variable). This is a pretty good coverage of static asset management strategies in React Native: https://willowtreeapps.com/ideas/react-native-tips-and-tricks-2-0-managing-static-assets-with-absolute-paths/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.