Home > Net >  React change state of checkbox
React change state of checkbox

Time:09-13

Class component - list of items with a boolean property ; I've added onChange method to change state of this propery in a collection. When I try to compile I have:

Line 15:59: Array.prototype.map() expects a return value from arrow function array-callback-return

import React from "react";

class ItemList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
       items: props.items
    }
  }

  toggleCompleted = (position) => {
    const updatedItems = this.state.items.map((item, idx) => {
      position === idx ? {...item, completed: !item.completed} : item //err
    })
    this.setState({
      items: updatedItems
    })
  }

  render() {
    return(
      <div className="col-12 col-lg-8 mx-auto">
      <h3 className="h3">Tasks</h3>
      {this.state.items.length > 0 &&
      <table className="table">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Title</th>
            <th scope="col">Description</th>
            <th scope="col">Completed</th>
          </tr>
        </thead>
        <tbody>
        {this.state.items.map((item, idx) => {
          return (
            <tr key={idx 1}>
              <th scope="row">{idx 1}</th>
              <td>{item.title}</td>
              <td>{item.description}</td>
              <td>
                <input 
                id={"completed".concat(idx)} 
                className="form-check-input"
                type="checkbox"
                checked={item.completed}
                onChange={() => {this.toggleCompleted(idx)}}/>
              </td>
            </tr>
          );
        })}
        </tbody>
      </table>
      }
    </div>
    )
  }
}


export default ItemList;

Why?

CodePudding user response:

Add missing return statement:

const updatedItems = this.state.items.map((item, idx) => {
  return position === idx ? {...item, completed: !item.completed} : item 
})

or remove {}

const updatedItems = this.state.items.map((item, idx) =>
  position === idx ? {...item, completed: !item.completed} : item 
)

Read more about basics here

CodePudding user response:

Add a "return" before

position === idx ? {...item, completed: !item.completed} : item
  • Related