mardi 26 novembre 2019

React JS Prevent onClick from Firing when Checkbox is checked

I have a Card component with checkboxes. When a user clicks on a card, another Suggest component opens. However, when user clicks on checkbox, the onClick function runs also, still opening the Suggestions component. If there are no suggestions then it returns, and in that case the checkboxes work fine. I tried using preventDefault and stopPropagation, which I included stopPropagation the code below. Any help greatly appreciated.

import React, { useState } from "react";

const onUpdateCB = (e,ischecked, loginuser, userid, setisChecked,handleCheck) => {
 e.stopPropagation();
  console.log(ischecked, loginuser, userid);

  fetch('http://localhost:3000/cb', {
      method: 'post',
      headers: {'Content-Type':'application/json'},
      body:JSON.stringify({
      loginuser,
      userid,
      ischecked: ischecked
    })
  }).then(setisChecked(ischecked));
  return

};

const Card = props => {
  const [isChecked, setisChecked] = useState(props.ischecked);
  return (
    <div
      className="pointer bg-light-green dib br3 pa3 ma2 shadow-5"
      onClick={() => props.handleClick(props.id)}

    >
      <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={isChecked}
          onChange={(e) =>
            onUpdateCB(e,!isChecked, props.loginuser.id, props.id, setisChecked)
          }
        />
      </div>
    </div>
  );
};

HandleClick function

handleClick(id) {
    const updatedSuggest = suggest.map(sugg => {
      if (sugg.id === id) {
        this.setState({
          suggest: suggest.filter(suggest => suggest.id === id),
          route: "suggestions"
        });
        this.setState({ routed: true });
        this.setState({
          networkfilter: this.state.network.filter(netw => netw.id === id),
          route: "suggestions"
        });
        this.setState({ routed: true });
      }
      return;
    });
  }



Aucun commentaire:

Enregistrer un commentaire