Search code examples
reactjsreact-nativereact-componentreact-native-svg

Mapping multiple react native components


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>

Solution

  • 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>