-1

I have a class component. on that component, I have a state item called tasks_array.

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

import Task from './component/task'

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tasks_array: [
                {id: 1 , name: 'item 1'},
                {id: 1 , name: 'item 1'},
                {id: 1 , name: 'item 1'},
                {id: 1 , name: 'item 1'},
                {id: 1 , name: 'item 1'},
                {id: 1 , name: 'item 1'},
            ]
        };
    
        
        
    }

    render() {
        return (
            <div>
                {this.state.tasks_array.map(function (item,index) {
                    return (
                        <Task
                            key={index}
                            myItem={item}
                            otherItems={this.state.tasks_array}
                        />
                    );
                })}
            </div>
        )
    }
}

export default App

the error is popping up : TypeError: Cannot read property 'state' of undefined

enter image description here

so the issue is in the line : otherItems={this.state.tasks_array} , where this is undefined .

can anyone help me to understand, what is the reason for this issue ?

and how to solve this issue to send the whole tasks_array as a property of Task component

subhadip pahari
  • 799
  • 1
  • 7
  • 16

1 Answers1

1

"this" is undefined inside map function Reactjs

Array.prototype.map() takes a second argument to set what this refers to in the mapping function, so pass this as the second argument to preserve the current context:

someList.map(function(item) {
  ...
}, this)

Alternatively, you can use an ES6 arrow function to automatically preserve the current this context:

someList.map((item) => {
  ...
})
Albin Cederblad
  • 175
  • 1
  • 11
  • really thank you for the answer. really helpful. can you help me to understand why es6 arrow function preserves the current state . any docs or something to read and understand. – subhadip pahari Oct 18 '20 at 18:47
  • sorry buddy i didn't downvote you :) Actually, i didn't know about this before as i've always used arrow function i never ran into this problem. It's is a matter of understanding the "this"-keyword in javascript and what it refers to in different contexts. – Albin Cederblad Oct 18 '20 at 19:02