Martin Nordström
Martin Nordström

Reputation: 6025

TypeError: Cannot read property of undefined | ReactJS

I want to use fields in my map() function, however I get this TypeError: Cannot read property 'fields' of undefined and I don't understand why. Because when I console.log(this.props.schema.fields) I get data printed out in my console.

Question

Why does is this happening? Is it because inside of the return() there is another scope? Or what..?

export default class ObjectDisplay extends Component {
  render() {
    console.log(this.props.schema.fields)
    //const { parentDocumentId, value, open, schema } = this.props
    return (
      <table>
        <tbody>
          {this.props.schema.fields.map((schema, i) =>
            <ObjectKeyDisplay
              key={i}
              schema={schema}
              value={(this.props.value || {})[schema.name]}
              parentDocumentId={this.props.parentDocumentId}
            />
          )}
        </tbody>
      </table>
    )
  }
}

I am really thankful for all the help.

Upvotes: 1

Views: 848

Answers (2)

Martin Nordstr&#246;m
Martin Nordstr&#246;m

Reputation: 6025

I was overriding my first constant schema with another constant named schema. Sorry for the misunderstandment!

Upvotes: 0

sohamdodia
sohamdodia

Reputation: 377

It is giving you error because when first time it renders it it not able to find the fields property. Try to put condition using ternary operator.

{
  this.props.schema.fields
       ?
        ... Map function 
       : <div></div>
} 

Upvotes: 3

Related Questions