Home > Mobile >  React - add props to a component represented by an object
React - add props to a component represented by an object

Time:08-18

Is it possible to add props to a component represented by an object? I would like to add those props only once, inside the map function, if possible.

children: [
    {
      id: '1',
      isActive: false,
      label: 'Home',
      component: <ReportsIcon height={30} width={30} />,
    },
    {
      id: '2',
      isActive: true,
      label: 'Dashboard',
      component: <SettingsIcon height={30} width={30} />,
    },
  ].map((item) => (
    <MenuLink key={item.id} isActive={false} label={item.label}>
      <a href={`#`}>
        {item.component // ADD PROPS HERE //}
        {item.label}
      </a>
    </MenuLink>
  )),

CodePudding user response:

Two options proposed by Njuguna Mureithi 1.

children: [
    {
      id: '1',
      isActive: false,
      label: 'Home',
      component: props => <ReportsIcon height={30} width={30} {...props} />,
    },
    {
      id: '2',
      isActive: true,
      label: 'Dashboard',
      component: props => <SettingsIcon height={30} width={30} {...props} />,
    },
  ].map((item) => (
    <MenuLink key={item.id} isActive={false} label={item.label}>
      <a href={`#`}>
        {item.component({ prop: 123 })}
        {item.label}
      </a>
    </MenuLink>
  )),
children: [
    {
      id: '1',
      isActive: false,
      label: 'Home',
      component: ReportsIcon,
    },
    {
      id: '2',
      isActive: true,
      label: 'Dashboard',
      component: SettingsIcon,
    },
  ].map((item) => (
    <MenuLink key={item.id} isActive={false} label={item.label}>
      <a href={`#`}>
        <item.component height={30} width={30} prop={123} />
        {item.label}
      </a>
    </MenuLink>
  )),
  • Related