user13824605
user13824605

Reputation:

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

Upvotes: 3

Views: 1319

Answers (3)

Marwen Trabelsi
Marwen Trabelsi

Reputation: 4257

.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.

Upvotes: 1

Dani
Dani

Reputation: 584

With this code, you assign a boolean to the previous array value. You cannot use the map function with a boolean

this.setState({
  teachers: !teachers
});

Upvotes: 0

Dennis Vash
Dennis Vash

Reputation: 53964

teachers is an array, on handleView you assign a boolean instead of an array, so in next render you trying to #Array.map() a boolean value which caused a runtime error.

// teachers is an array
let teachers = this.state.teachers;

// teachers will be a boolean after the render
// ![] === false
this.setState({
  teachers: !teachers,
});

I think you meant to use showPersons instead.

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

Edit withered-water-ji3lb

Upvotes: 0

Related Questions