Pass .js databases as a prop to a React Native component

34 Views Asked by At

I currently have an image slideshow showing up on my app. I first initialized the images in a images.js file.

export default [
  {
    id: 1,
    img: require("../AS_images/1.webp"),
  },

then I import this file as a dependency in my component Slider.js

import Images from "../assets/AS_images/images";

then I use it to render a flatlist and deal with the rest in a different component

  return (
    <View>
      <FlatList
        data={Images}
        renderItem={({ item }) => <SlideItem item={item} />}
     etc..

then this is being displayed in App.js by calling the main component

<SafeAreaView>
    <Slider />
  </SafeAreaView>

It works great, but I have 8 sets of image slideshows I need to display, and I don't really want to create 7 more Slider.js files for each individual. I'd rather want to pass a prop that would tell the component which set of images to use. For example:

<SafeAreaView>
<Slider path="Set2"/>
</SafeAreaView>

and in the Slider.js file, unpon receiving this prop it would adapt the routing accordingly:

import Images from "../assets/Set2/images";

The only part of the path that would need to be changed is the "Set2" bit. I plan to bundle all my images in their own separate folders under /assets/ and then within their respective folder to have this database that initializes them /assets/Set2/images.js

How would I go about doing that or doing something similar? Thank you in advance for your help.

I tried modifying import pathing and location but that obviously didn't work

Current Code App.js

  <SafeAreaView>
        <Slider path="AS" />
      </SafeAreaView>

Slider.js

import AS from "../assets/AS_images/images";

...

return (
    <View>
      <FlatList
        data={props.path}
        renderItem={({ item }) => <SlideItem item={item} />}
        horizontal
        pagingEnabled
        snapToAlignment="center"
        showsHorizontalScrollIndicator={false}
        onScroll={handleOnScroll}
        onViewableItemsChanged={handleOnViewableItemsChanged}
        viewabilityConfig={viewabilityConfig}
      />
      <Pagination data={props.path} scrollX={scrollX} index={index} />
    </View>
  );
1

There are 1 best solutions below

2
Feijoes On BEST ANSWER

You are passing data="AS" , not the AS files, this should work

import AS from "../assets/AS_images/images";
import BS from "../assets/BS_images/images";
const Slider = (props) => {
    return (
    <View>
      <FlatList
        data={props.path == "AS" ? AS : BS }
        renderItem={({ item }) => <SlideItem item={item} />}
        horizontal
        pagingEnabled
        snapToAlignment="center"
        showsHorizontalScrollIndicator={false}
        onScroll={handleOnScroll}
        onViewableItemsChanged={handleOnViewableItemsChanged}
        viewabilityConfig={viewabilityConfig}
      />
      <Pagination data={props.path} scrollX={scrollX} index={index} />
    </View>
  );
}

`