Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an error .map() is not a function

I am stuck at this error ".map is not a function"

TypeError
teachers.map is not a function


class toggleView extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      teachers: ["Willis", "Duke", "Davis", "Walter"],
      showPersons: false
    };
    this.handleView = this.handleView.bind(this);
  }

  handleView = e => {
    e.preventDefault();
    let teachers = this.state.teachers;
    this.setState({
      teachers: !teachers
    });
  };

  render() {
    let teachers = this.state.teachers;
    let individualTeacher = teachers.map(teacher => <li> {teacher} </li>);

    let person = null;
    if (this.state.showPersons === true) {
      person = <li>{individualTeacher}</li>;
    } else {
      person = null;
    }

    return (
      <div>
        <h3> Heloo folks </h3>
        <button onClick={this.handleView}>Toggle View</button>
        <br />
        <br />
        <ul>{person}</ul>
      </div>
    );
  }
}

code snippet link


1 Answers

.map is not a function

Is very common error message, it means that the object you are looping through is not an Array.

What you did in your code, is that when you click on the button and trigger the handleView you changed your teachers list in the state from a valid Array to something of boolean type:

let teachers = this.state.teachers;
this.setState({
  teachers: !teachers // here
});

After changing the state, React will quickly render the new state, but then find himself looping through a boolean instead of Array, thus trigger the error you are seeing.

Update

As one of the answers guessed, I think you are trying to change showPersons instead of teachers Array.

like image 155
Marwen Trabelsi Avatar answered Jul 07 '26 04:07

Marwen Trabelsi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!