-1

I have a class component in a reactjs project. The following code segment works fine. But inside the map function, I am not able to access the state variables. I am getting the below error,

TypeError: Cannot read properties of undefined (reading 'state')

Even console.log(this.state.total); didn't work inside the map function.

constructor(props) {
    super(props);
    this.state = {
        page: 2,
        total: 0,
    };
}

<Pagination>
{this.state.total > 0 ?
    Array(Math.ceil(this.state.total / 10)).fill(0).map(function (object, i) {
        
        return <Pagination.Item active={false} key={i}>{i + 1}</Pagination.Item>
    }).bind(this) : null}
</Pagination>
3
  • can it be that total in your state is still undefined on first render? How does your state look like? Does it have a default value that is a number? Commented Jul 9, 2022 at 13:47
  • yes it is set to 0 in the constructor. Later value is set after data is fetched. And as it is in the code, it will render if the value is >0 Commented Jul 9, 2022 at 13:55
  • Can you share the entire component code ? Commented Jul 9, 2022 at 14:34

1 Answer 1

1

Change the anonymous function in your map to an arrow function like this. Change from this:

map(function () {
  console.log(this.state)
  return ...
})

to this:

map(() => {
  console.log(this.state)
  return ...
})
Sign up to request clarification or add additional context in comments.

1 Comment

yes this solved my issue, thank you. I also had to remove " .bind(this)" from the map function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.