0

I have multiple react-native components (more than 100) each of which is different. To be more precise each component is actually a react-native svg component which looks like this

import * as React from "react";
import Svg, { Circle, Path } from "react-native-svg";

function SvgAlert(props) {
  return (
    <Svg
      width={24}
      height={24}
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      {...props}
    >
      <Circle cx={12} cy={16.75} r={1.25} fill="#000" />
      <Path fill="#000" d="M11 6h2v8h-2z" />
    </Svg>
  );
}

export default SvgAlert;

I want to import all these svgComponents from my component directory and render them in scrollview

<ScrollView>
  <SvgComp1>
  <SvgComp2>
  .
  .
  <SvgComp100>
<ScrollView>

Is there any way I can map through these components or any other approach to save the tedious work of importing each component one by one and rendering it manually (Like a map for components or something else)

<ScrollView>
  {
    components.map(Each=>{
       return <Each/>
      })
  }
<ScrollView>
Aman Gupta
  • 23
  • 6

2 Answers2

0

You could do the work of importing every svg just one time and then reuse it importing the array that contains all the svgs. Something like:

AllSvgs.js

import SVG1 from '...';
import SVG2 from '...';
import SVG3 from '...';
...

export default SVGsArray = [SVG1, SVG2, SVG3, ...];

Then in a component:

import SVGsArray from '../path/to/AllSvgs.js';
...

<ScrollView>
  {
    SVGsArray.map(Each)=>{
       return <Each/>
  }
<ScrollView>
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
0

What I have Worked is a little bit different, we can import all the components into a single file and store them in Object format So that we can access anywhere you want, for example of Object

import A from 'path/to/aComponent';
import B from 'path/to/bComponent';
import C from 'path/to/cComponent';
import D from 'path/to/dComponent';

export const SVGComponents = {
   aComponent: A,
   bComponent: B,
   cComponent: C,
   dComponent: D,
}

When you try to render try to read from the Object and Render it

import SVGComponents from 'path/to/SVGComponents';

<ScrollView>
    {
        components.map(name)=>{
        return <SVGComponents[name] />
    }
<ScrollView>

You can store these components any import anyWhere you need but you do have constant NAME

Raviteja V
  • 344
  • 2
  • 7