0

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?

1
  • Use parts={props.parts[0]}, as you showed in example, props is an object with key as parts. Commented Nov 2, 2021 at 4:46

2 Answers 2

1
// 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])
Sign up to request clarification or add additional context in comments.

Comments

0

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>
      )  
}

3 Comments

it same: const parts = props.parts;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.