Andreas
Andreas

Reputation: 1479

Not being able to use an array sent in via props

Im sending in an array via props to a component, but i cant use map on the array. It says that

.map is not a function

My code:

const AuthorList = (authors) => {
return(
    <table className="table">
        <thead>
            <tr>Firstname</tr>
            <tr>Lastname</tr>
        </thead>
        <tbody>
            {authors.map(author => 
                <AuthorListRow key={author.id} author={author} />
            )}
        </tbody>
    </table>
);
};

This is what the Chrome React dev tool looks like:

enter image description here

Upvotes: 0

Views: 43

Answers (2)

max
max

Reputation: 6069

Props will be passed in as an object, so right now authors is acting as an alias for props. Accessing the authors property on props should work as long as that prop is being declared with an array.

const AuthorList = (props) => {
  return(
     // ..
            {props.authors.map(author => 
                <AuthorListRow key={author.id} author={author} />
            )}
     // ..
 );
};

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 104539

Issue is, whenever you pass any data from parent to child, it get passed through props, and you need to receive the props in child component and access the specific values, write it like this:

const AuthorList = (props) => {
return(
    <table className="table">
        <thead>
            <tr>Firstname</tr>
            <tr>Lastname</tr>
        </thead>
        <tbody>
            {props.authors.map(author => 
                <AuthorListRow key={author.id} author={author} />
            )}
        </tbody>
    </table>
);
};

or

const AuthorList = ({authors}) => {
    return(
        <table className="table">
            <thead>
                <tr>Firstname</tr>
                <tr>Lastname</tr>
            </thead>
            <tbody>
                {authors.map(author => 
                    <AuthorListRow key={author.id} author={author} />
                )}
            </tbody>
        </table>
    );
};

Reason why 2nd one is working: because props is an object, when you write {authors} it means you are receiving only authors value from object props. In that case you don't need to write props.authors.

Check this example:

obj = {a:1,b:2,c:3}
let {a} = obj;
console.log(a);

Upvotes: 2

Related Questions