dimanche 5 janvier 2020

How can I get my component to calculate the sum of checkbox values in React?

This application renders a list of foods with checkboxes next to them. I have a component that should calculate and display the sum of the checkbox values when they're checked. I am not able to display the values from the checkboxes.

This is currently what I have.

This file renders a list of foods with checkboxes next to each.

import React from "react";
import { Card, Accordion } from "react-bootstrap";

const Cards = props => {
  return (
    <Accordion defaultActiveKey="0">
      <Card>
        <Accordion.Toggle as={Card.Header} eventKey={`${props.key}`}>
          <input
            type="checkbox"
            value={props.calories}
          />{" "}
          {props && props.title + " : " + props.calories + "cal"}
        </Accordion.Toggle>

        <Accordion.Collapse eventKey={`${props.key}`}>
          <Card.Body>
            {" "}
            {props.obj.nutrients &&
              "fat: " + props.obj.nutrients["fat"]} ||{" "}
            {props.obj.nutrients &&
              "trans fats: " + props.obj.nutrients["transfat"]}
          </Card.Body>
        </Accordion.Collapse>
      </Card>{" "}
    </Accordion>
  );
};

export default Cards;

I would like for this component to do the sum with the value from input box which is "props.calories" in the Cards component. This is what I've tried so far.

import React from 'react';
import Cards from './card';


class Calculator extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isChecked:false
        };
        this.handleChecked = this.handleChecked.bind(this);
    }

    handleChecked() {
     this.setState({isChecked: !this.state.isChecked});
    }



    render() {
            var total;
            if (this.state.isChecked) {
                total += <Cards.input.value/>;
            } 

        return (
            <div>
            <h1>Total: {total}</h1>
            </div>


        );
    }
}


export default Calculator;


I'm brand new to React and any help would be appreciated. Thank you.




Aucun commentaire:

Enregistrer un commentaire