简体   繁体   中英

Pass in object as prop react

I have a function class:

function TopicBox({topicName, article1}) {
    return (
        <div className="TopicBox">
            <h1>{topicName}</h1>
            <div className="topicDivider" />
            <Article 
                    articleImageLink={article1.imageLink} />

--MORE CODE--
export default TopicBox

As you can see it takes in the props topicName, which is just a string, and article1 which is an object. article1 variable will have child components, such as.imageLink as seen on the last line of code. Now on another file called I want to create a topic box like such:

<TopicBox topicName="Hi" 
                        article1={imageLink:"google.com",
                                title:"hi"}/>

So again the topicName prop is just a string, so that works fine. Now I'm creating a new object called article1 that contains the child variable imageLink. However this code doesn't work. I get the following error:

Parsing error: Unexpected token, expected "}"

  10 |             <div className="TopicLists">
  11 |                 <TopicBox topicName="Hi" 
> 12 |                         article1={imageLink:"google.com",
     |                                            ^
  13 |                                 title:"hi"}/>
  14 |                 <TopicBox />

So to debug, I tried replacing the: to a = when I create the child object, but I get another error:

'imageLink' is not defined.eslintno-undef

Can you please let me know how to pass in an object as a prop?

Thanks!

Try this way

<TopicBox
  topicName="Hi"
  article1={{ imageLink: "google.com", title: "hi" }}
></TopicBox>

You can do it like this;

const article1 = {imageLink: "google.com", title: "hi"}
<TopicBox
  topicName = "Hi"
  article1 = {article1} />

Another way you can do this is by passing an object property as individual props using spread operator;

const article1 = {imageLink: "google.com", title: "hi"}
<TopicName 
  topicName = "Hi"
  {...article1} />

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