Getting an error .map() is not a function

Viewed 595

Hi am a newbie to react but am stuck at this error " .map is not a function" need assistance

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

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

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

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
});
Related