0

I am making a cooking app that adds up the total amount of ingredients for each recipe the user adds. For example, the user adds "Cheese Burger" as the title and in that component it would have an input box to type in name of the ingredient then another input field for the amount of ingredients. At the end of the program I want to allow the user to click a button called "Add/Build Grocery list" at the end, but unsure how to match the different ingredients to the number value of that ingredient.

0

1 Answer 1

1

You mean something like this might help?

import React, { Component } from "react";
import "./styles.css";

class App extends Component {
  state = {
    Items: {},
    CurItem: "",
    Quantity: 0
  };
  render() {
    return (
      <div className="App">
        <form
          onSubmit={(e) => {
            e.preventDefault();
            const Items = { ...this.state.Items };
            if (typeof Items[this.state.CurItem] === "undefined") {
              Items[this.state.CurItem] = +this.state.Quantity;
            } else {
              Items[this.state.CurItem] += +this.state.Quantity;
            }
            this.setState({
              Items,
              CurItem: "",
              Quantity: 0
            });
          }}
        >
          <label>
            <strong>Item Name:</strong>
            <input
              type="text"
              value={this.state.CurItem}
              onChange={(e) => this.setState({ CurItem: e.target.value })}
            />
          </label>
          <label>
            <strong>Quantity:</strong>
            <input
              type="number"
              value={this.state.Quantity}
              onChange={(e) => this.setState({ Quantity: e.target.value })}
            />
          </label>
          <input type="submit" />
        </form>
        <table border="1" width="50%">
          <thead>
            <tr>
              <th>Item</th>
              <th>Quantity</th>
            </tr>
          </thead>
          <tbody>
            {Object.keys(this.state.Items).map((item) => (
              <tr>
                <td>{item}</td>
                <td>{this.state.Items[item]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
}

export default App;

See demo here: https://j6fv7.csb.app/

Preview

preview

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.