Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Component from JS Object as props in React

I'm reading from a JS object (from JSX) and trying to pass value of a component but it's rendered as string.

I tried placing components (in icon key of data see below) in {} but that doesn't help as data gives an error.

Here's the simplified version of the files.

data.js as below:

const data = [
 {
    title: "some title",
    desc: "some desc",
 },
 [
   {
     icon: "<TwitterIcon />",
     title: "title 1",
     desc: "desc 1",
   },
   {
     icon: "<FacebookIcon />",
     title: "title 2",
     desc: "desc 2",
   },
 ],
]

export { data }

index.js that reads data object and passes as props to AnotherComponent:

import { data } from "../path/to/data"
import AnotherComponent from "../path/to/AnotherComponent"

const Homepage = () => {

  return (
    <AnotherComponent {...data} />
  )
}

AnotherComponent.jsx as below:

import {TwitterIcon, FacebookIcon} from "../path/to/CustomIcons"

const AnotherComponent = ({ ...data}) => {

  return (
    {data[1].map(item => (
      <div>{item.icon}</div> // this prints string as opposed to rendering the component
      <div>{item.title}</div>
      <div>{item.desc}</div>
    ))}
  )
}

index.js returns:

<div><TwitterIcon /></div>
<div>title 1</div>
<div>desc 1</div>
<div><FacebookIcon /></div>
<div>title 2</div>
<div>desc 2</div>
like image 237
megatower Avatar asked Dec 19 '25 13:12

megatower


1 Answers

In the object you are defining as:

{
  icon: "<TwitterIcon />",
  title: "title 1",
  desc: "desc 1",
}

Don't use "<TwitterIcon />" It will always return a string, instead use TwitterIcon:

{
  icon: TwitterIcon,
  title: "title 1",
  desc: "desc 1",
}

And finally, call it where you need it, in this way:

const AnotherComponent = ({ ...data}) => {

  return (
    {data[1].map(item => (
      <div><item.icon /></div> // HERE: check I'm calling item.icon as React Component
      <div>{item.title}</div>
      <div>{item.desc}</div>
    ))}
  )
}

In this way you are passing the icon to anywhere you want and not just passing a string. So, you can call it as a Component when you need it to render. I do it a lot in my work.

like image 148
Hector Avatar answered Dec 21 '25 04:12

Hector



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!