ghostrider
ghostrider

Reputation: 2238

TypeError: Cannot read property “0” from undefined

I am a beginner in ReactJS and below is the sample program that I am trying to run:

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Person from './Person/Person';

class App extends Component {

state = {

persons : [
{ name: 'John' , age:20 },
{ name: 'Jack' , age:29 }

]

}

  render() {
    return (
      <div className="App">
        <h1>Yo mama</h1>
        <p>hmm</p>
        <button>Switch </button>
        <Person name={this.state.persons.name[0]} age ={this.state.persons.age[0]}/> 
        <Person name={this.state.persons.name[1]} age ={this.state.persons.age[1]}/>
      </div>

    );


  }
}

export default App;

Person.js

import React from 'react';

const Person = (props) => {
return(
<div>
<p>Hey Saurabh, Whats up</p>
<p>{props.name}</p>

</div>
);

};

export default Person;

While running I am getting the below error in the browser

TypeError: Cannot read property '0' of undefined

at line :

<Person name={this.state.persons.name[0]} age ={this.state.persons.age[0]}/> 

Can someone please help

Upvotes: 0

Views: 158

Answers (3)

Sushanth --
Sushanth --

Reputation: 55740

As the other answers pointed out, you are trying to access, a property 0 on name and age. But you want to access each item in the array.

This would work if name and age is an object

name: {
   "0": 'Bad Name'
}

age: {
   "0": 'Bad Age'
}

But it is a primitive in this case ( string and number ) This can also be written in these lines.

<button>Switch </button>
{
  this.state.persons.map(person => {
      // each iteration is the item in the array
      // which is the person in this case
      const {
        age,
        name
      } = person;

      return (
        <Person name={name} age ={age} key={name}/> 
      )
  });
}

Upvotes: 2

mikeb
mikeb

Reputation: 11267

You are not referencing your array item correctly:

this.state.persons.age[0] <- This says age is an array, which it's not, which gives you an array error.

persons is the actual array. Try this:

this.state.persons[0].age

Upvotes: 1

Jeremy Harris
Jeremy Harris

Reputation: 24549

Persons, in this case is the array, so instead of:

this.state.persons.name[0]

It should be:

this.state.persons[0].name

Upvotes: 3

Related Questions