Home > database >  How to map array of objects with components and pass props these components?
How to map array of objects with components and pass props these components?

Time:08-11

I have many icon components with the same structure:

const DeliveryIcon: React.FC<IFavoriteIconProps> = ({ width = 20, height = 20, filled = false, fill = '#222222' }) => {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      height={width}
      width={height}
      viewBox="0 0 48 48"
      fill={filled ? '#f44336' : fill}
    >
      <path d="..." />
    </svg>
  );
};

Then in some component I made an array of objects which I'd like to render:

const data = [
  {
    id: 1,
    name: 'Delivery',
    icon: <DeliveryIcon fill={'#6bc553b0'} width={28} height={28} />,
  },
  {
    id: 2,
    name: 'Prices',
    icon: <Price fill={'#6bc553b0'} width={28} height={28} />,
  },
];

const InfoBlock: React.FC = () => {
  return (
    <div className={classes['info-block']}>
      {data.map((item) => (
        <div className={classes['info-block-item']} key={item.id}>
          {item.icon}
          {item.name}
        </div>
      ))}
    </div>
  );
};

How can I pass prop fill, width and height to icon component in map render function instead of repeating it in array of objects?

CodePudding user response:

Just giving another option, without the icon object being instantiated on the data array.

const data = [
  {
    id: 1,
    name: 'Delivery',
    Icon: DeliveryIcon
  },
  {
    id: 2,
    name: 'Prices',
    Icon: Price
  },
];

const InfoBlock: React.FC = () => {
  return (
    <div className={classes['info-block']}>
      {data.map(({id, name, Icon}) => (
        <div className={classes['info-block-item']} key={id}>
          <Icon fill={'#6bc553b0'} width={28} height={28} />
          {name}
        </div>
      ))}
    </div>
  );
};

CodePudding user response:

The best that I can think of is:

const iconProps = {
  fill: '#6bc553b0',
  width: 28,
  height: 28
}
const data = [
  {
    id: 1,
    name: 'Delivery',
    icon: <DeliveryIcon {...iconProps} />,
  },
  {
    id: 2,
    name: 'Prices',
    icon: <Price {...iconProps} />,
  },
];

The data array unfortunately isn't just plain objects but includes JSX so we can't later modify the icons themselves in array.map() because the icon components have already been instantiated by this time. I am not sure if instantiated is the right word for this but once we write JSX, we have basically called React.createElement() and can no longer pass props.

  • Related