'How can I calculate the price according to the entered quantity and sum its total as well?

I have this data:

const products = [
  {
    prodName: "Tumbler",
    price: 1.5,
    size: "500",
    colorMap: { Black: 20, Pink: 10, Green: 5 },
    id: "aRLMZkiSU7T0lcsPCSsV"
  },
  {
    prodName: "Shirt",
    price: 2.0,
    size: "L",
    colorMap: { Blue: 10, Black: 10 },
    id: "uTHIR6OQFRuqP9Drft0e"
  },
  {
    size: "200",
    price: 2.0,
    colorMap: { Green: 50, Red: 19, Black: 20 },
    prodName: "Notebook",
    id: "y9ECyZBKp2OBekmWym4M"
  }
];

I have a dynamic form where users can add a product and enter a quantity and choose a color. The user can also add more products and the process will be the same.

How can I calculate the total (product price * quantity entered) per item and also the sum of the total? Any help would be appreciated. Thank you.

Recreated this in codesandbox: https://codesandbox.io/s/react-hook-form-wizard-form-from-reddit-with-data-ouy64e?file=/src/fieldArray.js:322-770

NestedField component: This is where the quantity and the colors are:

const NestedArray = ({ nestIndex, control, register }) => {
  const { fields, remove, append } = useFieldArray({
    control,
    name: `order[${nestIndex}].variation`
  });

  const options = [
    { label: "red", value: "red" },
    { label: "green", value: "green" },
    { label: "blue", value: "blue" }
  ];

  return (
    <div>
      {fields.map((item, k) => {
        return (
          <div key={item.id} style={{ marginLeft: 20 }}>
            <label>{k + 1}</label>
            <label>Quantity:</label>
            <input
              type="number"
              {...register(`order[${nestIndex}].variation[${k}].qty`, {
                valueAsNumber: true
              })}
            />

            <Controller
              control={control}
              name={`order[${nestIndex}].variation[${k}].color`}
              render={({ field: { onChange, value = "", ...rest } }) => (
                <Autocomplete
                  {...rest}
                  onInputChange={(e, newValue) => {
                    onChange(newValue);
                  }}
                  inputValue={value}
                  options={options}
                  isOptionEqualToValue={(option, value) =>
                    option?.value === value?.value
                  }
                  // getOptionLabel={(option) => option?.label ?? ""}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Color"
                      variant="outlined"
                      fullWidth
                    />
                  )}
                />
              )}
            />

            <span>Price: Qty * price</span>

    </div>
  );
};

export default NestedArray;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source