Home > OS >  How can I pass props to JSX reference?
How can I pass props to JSX reference?

Time:04-27

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?

CodePudding user response:

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>
     )
   })
}
  • Related