Dylan Bozarth
Dylan Bozarth

Reputation: 1694

Mapping from passed props in a functional component

I am building a website that is reliant on a json file for all of its information. In my app.js the json info is showing properly when I console.log() it, but when I try and pass it to my functional components it is giving me undefined.
in app.js

<Route
  exact
  path="/puppies"
  render={props => (
    <Puppies {...props} propdata={this.state.propdata} />
  )}
/>

This seems to be working fine, however when I try and map it inside the component it tells me that its undefined.

function Puppies(propdata) {
  return <div>{propdata.puppies.map(puppies => 
    <h1>{puppies.name}</h1>
  )}</div>;
}

I have done this before but with a class component. So most likely I am making a mistake with the functional component. The full code is viewable here: https://github.com/Imstupidpleasehelp/Puppywebsite/tree/master/src
Thank you for your time.

Upvotes: 0

Views: 1126

Answers (3)

Abraham
Abraham

Reputation: 9875

You'll probably need to check that the data is null of undefined. You are passing a big object with data, I recommend to pass more specific props instead of a big object.

I like to prevent my data to be undefined in 2 ways:

Usage:

import _ from 'lodash';

function Puppies({ propdata }) {
  const puppies = _.get(propdata, 'puppies', []);

  return (
    <div>
      {puppies.map(puppies => <h1>{puppies.name}</h1>)}
    </div>
  );
}

or

function Puppies({ propdata }) {
  const puppies = propdata?.puppies || [];

  return (
    <div>
      {puppies.map(puppies => <h1>{puppies.name}</h1>)}
    </div>
  );
}

Upvotes: 2

sgrmhdk
sgrmhdk

Reputation: 236

Since this is asynchronous request to get the data, your data is not readily available hence you need to handle that scenario.

function Puppies(propdata) {
return (
{
propdata.puppies.length>0 ? <div>

propdata.puppies.map((puppies)=>{
     <h1>{puppies.name}</h1>
})
</div> :null
 }
)

Upvotes: 0

Nate Levin
Nate Levin

Reputation: 1118

What you have as propdata is actually just an object containing all properties that you have passed in. You should use destructuring to get the actual propdata value.

Solution:

function Puppies({propdata}) {
  return (
    <div>
      {propdata.puppies.map(puppies => 
        <h1>{puppies.name}</h1>
      )}
    </div>
  );
}

Upvotes: 0

Related Questions