DaOneRom
DaOneRom

Reputation: 294

How to rewrite redundant method declaration and create a shorter one?

I have declared identical const values (sort of). Here's what I have so far...

import React from 'react'

function Component_a() {
   const x = 5;
   const y = 10;
   const image_a = [...Array(x)].map((e, i) =>
       <div className="image" key={i}>
           <img src="img/image.png" alt="" />
       </div>
   )
   const image_b = [...Array(y)].map((e, i) =>
       <div className="image" key={i}>
           <img src="img/image.png" alt="" />
       </div>
   )
   return (
      {/*some more codes*/}
   )
}

export default Component_a

It's a bit annoying to look at especially when I add more redundant lines like this. Thanks for your help.

Upvotes: 0

Views: 45

Answers (2)

Code Maniac
Code Maniac

Reputation: 37745

One is to do something like this, club both of the arrays in single array and loop through them

const [image_a,image_b] = [[...Array(x)],[...Array(y)]].map((v, i) =>
        v.map((e,i)=>
       <div className="image" key={i}>
           <img src="img/image.png" alt="" />
       </div>
     )
 )

Another approach: If there are many such arrays you should use a functional approach

let getHtml = (arr) => arr.map((e,i)) =>
                     <div className="image" key={i}>
                        <img src="img/image.png" alt="" />
                     </div>

And then pass the array to it

   let image_a = getHtml(array1)

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370929

Because the only thing that looks to change is the length of the array, just create a function out of it, and call that function twice (or as many times as you need):

const makeImages = length => Array.from(
  { length },
  (_, i) => (
    <div className="image" key={i}>
      <img src="img/image.png" alt="" />
    </div>
  )
);

function Component_a() {
   const x = 5;
   const y = 10;
   const image_a = makeImages(x);
   const image_b = makeImages(y);
   return (
      {/*some more codes*/}
   )
}

Upvotes: 1

Related Questions