0

I'm trying to send the corresponding name of an img down as a prop to a child like so:

      <Page
        item={item}
        translateX={translateX}
        index={index}
        key={item.route}
      />

Where the item object has a prop called name, with the name of the img like so:

  {
    route: "ReactQuiz",
    bgColor: "#88dded",
    secondary: "#7cc5d9",
    fontColor: "#1c2c4c",
    name: "React",
  },

And I'm trying to use the img in my Page component:

import { Dimensions, StyleSheet, Text, View, Image } from "react-native";
import React from "react";
import Animated, {
  Extrapolate,
  interpolate,
  useAnimatedStyle,
} from "react-native-reanimated";
import RectangleButton from "./RectangleButton";

interface PageProps {
  item: {
    route: any;
    bgColor: string;
    fontColor: string;
    secondary: string;
    logo?: React.ReactNode;
    name: string;
  };
  index: number;
  translateX: Animated.SharedValue<number>;
}

const { width, height } = Dimensions.get("window");
const SIZE = width * 0.7;

const Page: React.FC<PageProps> = ({ item, index, translateX }) => {

  return (
    <Animated.View
      style={[
        styles.container,
        { backgroundColor: `${item.bgColor}` },
      ]}
    >
      <View
        style={{
          height: height * 0.5,
          justifyContent: "space-between",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <Image source={require(`../assets/${item.name}.png`)} />
      </View>
    </Animated.View>
  );
};

export default Page;

const styles = StyleSheet.create({
});

It's not the name of the img that's incorrect, nor the format (all images in my data are png).

But react is screaming at me and telling me it can't be done. How else can I dynamically generate images from data?

Mathew
  • 318
  • 11
  • 1
    This might be helpful: https://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names or this https://stackoverflow.com/questions/44991669/react-native-require-with-dynamic-string TL;DR: you can't have dynamic paths for `require` – poPaTheGuru Aug 25 '23 at 18:56
  • 1
    https://stackoverflow.com/a/76529640/14738120 – Ahmed5G Aug 25 '23 at 19:07
  • 1
    Does this answer your question? [React Native - Image Require Module using Dynamic Names](https://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names) – user18309290 Aug 26 '23 at 04:48

0 Answers0