0

To preface, I am working on this for an internship on a very large codebase in which I am not responsible for making design changes. If it were up to me, I would look for a better way to achieve this, but it's not. So I am requesting you guys don't suggest I change the entire implementation unless what I'm asking is completely impossible.

I have an object that looks something like:

const object = {
   option1: {
     url: "...",
     icon: <Icon1 />
   },
   option2: {
     url: "...",
     icon: <Icon2 />
   }
}

In the UI, it is being rendered as follows:

{
   Object.keys(object).map(( option, idx ) => {
     return (
       <Component>
          {
            option.icon
          }
       </Component>
     )
   })
}

I'm looking for a way to pass props to the option.icon? The icons are different. Is this possible?

Ammar Ahmed
  • 344
  • 3
  • 11
  • This is like asking if you can change the output of calling a function `foo()` with different parameters; it just doesn't work out or make sense. – kelsny Apr 26 '22 at 18:40
  • @kellys this comparison isn't relevant as [React elements could be cloned with more props](https://stackoverflow.com/q/32370994/1218980), which is another solution used when you have no control over the input (receiving a React node instead of a component) – Emile Bergeron Apr 26 '22 at 18:58

1 Answers1

2

option.icon is the result of calling <Icon>. You need to pass them props when you write the JSX.

It's essentially the same as:

option1: {
  url: "...",
  icon: Icon1()
},

… and then deciding you want to have passed arguments to Icon1() later on. You can't when you only have the return value to work with.

If you want to pass props later, then you need to assign the component to option.icon instead so you can write the JSX at the time you want to pass the props.

const object = {
   option1: {
     url: "...",
     icon: Icon1
   },
   option2: {
     url: "...",
     icon: Icon2
   }
}

{
   Object.values(object).map(( option, idx ) => {
     const IconComponent = option.icon;

     return (
       <Component>
          <IconComponent propName={propValue} />
       </Component>
     )
   })
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335