dimanche 20 octobre 2019

React Unable to Change Checkboxes

When I click on the checkboxes coming from an array with field isChecked nothing happens. the handleChange() apparently not working. Everything seems to map ok, because the checkboxes that are set to true or false initially show correctly. None of the fields showed up checked until I added isChecked= {network[i].isChecked}. But now i can't check or uncheck. Where did I mess up?

App.js

import React, {Component} from 'react';
import NetworkArray from './components/NetworkArray';
import {network} from './NetworkData'
import './App.css';
import 'tachyons';

class App extends Component  {

    constructor() {
    super()
    this.state = {
    network: network,
    searchfield:'',

}
this.handleChange=this.handleChange.bind(this);

}


handleChange(id) {
  this.setState(prevState => {
    const updatedNetwork = prevState.network.map(netw => {
      if (netw.id === id) {
        netw.isChecked = !netw.isChecked
      }
      return netw
    })
    return {
      network:updatedNetwork
    }
  })
}
render() {
  const filteredNetwork = this.state.network.filter(netw => {
    return netw.lastName.toLowerCase().includes(this.state.searchfield.toLowerCase())
  })

  return (

      <div>

         <NetworkArray 
             network={filteredNetwork}
             handleChange = {this.handleChange}  />
      </div> 

    )
}

}
export default App;

CardComponent

import React from 'react';

const Card = (props) => {

    return(
        <div className = 'bg-light-green dib br3 pa3 ma2 grow  shadow-5'>

        <div>
            <h3>{props.name}</h3>
            <p>{props.company}</p> 
            <p>{props.phone}</p>
            <p>{props.email}</p>
            <p>{props.city}</p> 

         </div>
         <div> 
            My Network
            <input className ="largeCheckbox"
                type = "checkbox"
                checked={props.isChecked}
                onChange={()=> props.handleChange(props.id)}
                    /> 
            </div> 
         </div> 

        )
}

export default Card;

NetworkArray.js

    import Card from './Card';

    const NetworkArray = ({network,handleChange}) => {
        const cardComponent = network.map((user,i) => {
            return(
            <Card 
                key = {network[i].id}
                name = {network[i].firstName + ' ' + network[i].lastName} 
                company = {network[i].company}
                phone= {network[i].phone}
                email={network[i].email}
                city = {network[i].city}
                isChecked= {network[i].isChecked}
                handleChange={handleChange}

                />

                        )
        })
            return ( 
                    <div> 

                     {cardComponent}


                    </div> 
                )
    }

    export default NetworkArray;



Aucun commentaire:

Enregistrer un commentaire