brooksrelyt
brooksrelyt

Reputation: 4025

{props.props.title}? Why not {props.title}?

I am still learning how to use API data with react and nextjs. But, why does my function only work when I write {props.props.title} instead of, what I would expect, {props.title}?

Code:

function testItems(props) {
  console.log(props)
  return (
    <div className="col-md-6 d-flex align-items-stretch">
      <div className="card">
        <div className="card-body">
          <h1 className="card-title">{props.props.title}</h1>
        </div>
      </div>
    </div>
  )
}

export default testItems

Did I miss something when reading about calling props?

I am calling testItems as a hit for algolia react-instantsearch:

const InfiniteHits = ( {hits, refineNext, hasMore} ) => {
  return(
    <div className="row">
      {hits.map((hit, index) => (
        <Hits props={hit} key={index} />
      ))}
      {hasMore &&
        <button className="ais-InfiniteHits-loadMore" onClick={refineNext}>Show more</button>
      }
    </div>
  )
};

Upvotes: 2

Views: 1714

Answers (3)

Adam LeBlanc
Adam LeBlanc

Reputation: 962

I believe what is happening is you are passing a prop into your component that is called props, which is an object that has a property called props ({props: {title: "some title"}})

If you want to get it as prop.title you can just spread the properties like so

<Hit {...hit}, key={index} />

That will pass each key on props in as a prop.

Upvotes: 3

Muhammad Hassan Khan
Muhammad Hassan Khan

Reputation: 149

You are passing props as a prop in your component. If you want to use props only one time or either want not to use it anymore. You can use destructuring in your testItems component like function testItems({props}) or pass title and other props, if any, in your Hit component like <Hit title={hit.title} key={index} />.

Upvotes: 0

Saikat Das
Saikat Das

Reputation: 368

This is where the issue is

<Hits props={hit} key={index} />

You're supposed to pass it like this

<Hits hit={hit} key={index} />

Upvotes: 3

Related Questions