react class component state data is not available under map function under render function

653 Views Asked by At

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

1

There are 1 best solutions below

2
On

"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) => {
  ...
})