简体   繁体   中英

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>

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.

I think you should pass directly the icon component in the object , like this:

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

Then in index.js you can do (it is more clear to pass down props like this):

const Homepage = () => {
  return (
    <AnotherComponent data={data} />
  )
}

In AnotherComponent.jsx now you can do:

const AnotherComponent = ({data}) => {
  return (
    {data[1].map(item => (
      <div>{item.icon}</div>
      <div>{item.title}</div>
      <div>{item.desc}</div>
    ))}
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM