Home > Software engineering >  get undefined for array element react
get undefined for array element react

Time:11-02

I'm getting undefined when accessing element of array but console showed value when using the array name only. The code:

const Part = (props) => {
  return <p>{props.name} {props.exercises}</p>
}

const Content = (props) => {

  // when i use console.log(props[0])
  // it shows undefined
  // 
  // but when i use console.log(props)
  // it shows the array information as 
  // {parts: Array(3)}
  // parts: Array(3)
  // 0: {name: 'Fundamentals of React', exercises: 10}
  // 1: {name: 'Using props to pass data', exercises: 7}
  // 2: {name: 'State of a component', exercises: 14}
  // length: 3
  // [[Prototype]]: Array(0)
  // [[Prototype]]: Object

  return (
    <div>
       <Part parts={props[0]} />
    </div>
  )
}

const App = () => {
  const course = 'Half Stack application development'
  const parts = [
    {
    name: 'Fundamentals of React',
    exercises: 10
    },
  
   {
    name: 'Using props to pass data',
    exercises: 7
    },
  
  {
    name: 'State of a component',
    exercises: 14
  }
  ]

  return (
    <div>
      <Content parts={parts} />
    </div>
  )
}

So I don't understand why in Content, console.log(props) returns array info but console.log(props[0])says undefined, which gets nothing in App.


Update: Thanks for everyone's reply. Now I know if I use 'props.parts' inside Content, I will get the right result. Then I got another question (Sorry I'm new to JS and React) : Because 'parts' is defined in App and passed to Content. I shouldn't use or know 'parts' when defining Content. So why do I need to use 'props.parts' inside Content?

CodePudding user response:

// when i use console.log(props[0])
// it shows undefined

because the array variable name is parts as you have mentioned here:

// but when i use console.log(props)
// it shows the array information as 
// {parts: Array(3)}
// parts: Array(3)

So try this:

console.log(props.parts)

or

console.log(props.parts[0])

CodePudding user response:

console.log(props) not return array, it return object has 1 attribute name parts(parts is array)

=> Solution:

const Content = props => {
      const { parts } = props;
      return (
          <div>
             <Part parts=parts[0] />
          </div>
      )  
}
  • Related