I'm getting an undefined error in my project made with React

I am sending as a prop an array of objects. When I console.log(this.props) I get the array of objects, but when I try to assign it to a variable it gives me

TypeError:ninjas is undefined

This is how i send the prop

import React from 'react';
import Ninjas from './Ninjas';

class App extends React.Component {
  state = {
    ninjas:[
      {name:"Ryu",age:"20",belt:"black",key:"1"},
      {name:"Yoshi",age:"22",belt:"yellow",key:"2"},
      {name:"Mario",age:"25",belt:"white",key:"1"}
    ]
  }
  render(){
  return (
    <div>
      <h1>My first React App</h1>
      <Ninjas list={ this.state.ninjas }/>
    </div>
  )
  }
}

export default App;

And this is how i recibe it

import React from 'react';

class Ninjas extends React.Component {
    render(){
        const { ninjas } = this.props;
        const ninjasList = ninjas.map(ninja => {
            return(
                <div className="ninja" key={ ninja.key }>
                <div>Name: { ninja.name }</div>
                <div>Age: { ninja.age }</div>
                <div>Belt: { ninja.belt }</div>
                </div>
            )
        })
        return (
            <div className="ninja-list">
                { ninjasList }
            </div>
        );
    }
}

export default Ninjas;

Upvotes: 1

Views: 95

Answers (2)

klugjo
klugjo

Reputation: 20885

<Ninjas list={ this.state.ninjas }/>

I suggest you change this to

<Ninjas ninjas={ this.state.ninjas }/>

Otherwise the name would be list in your child component.

In other words the name of the property you use when rendering the component (here in the render function of App) has to correspond to the name you get from the props object in your child component (here your child component is Ninjas).

Upvotes: 2

Amrendra Nath
Amrendra Nath

Reputation: 74

You are passing ninjas in your Ninjas component <Ninjas list={ this.state.ninjas }/> using list props. So, you should be using this const { list } = this.props; instead of const { ninjas } = this.props; in your Ninjas Component.

import React from 'react';

class Ninjas extends React.Component {
    render(){
        const { list } = this.props;
        const ninjasList = list.map(ninja => {
            return(
                <div className="ninja" key={ ninja.key }>
                <div>Name: { ninja.name }</div>
                <div>Age: { ninja.age }</div>
                <div>Belt: { ninja.belt }</div>
                </div>
            )
        })
        return (
            <div className="ninja-list">
                { ninjasList }
            </div>
        );
    }
}

export default Ninjas;

Upvotes: 1

Related Questions