0

I am attempting to update a state in the parent class based on a change that occurs in the child class, but I can't seem to get it to work. It compiles without a problem, but when I hit the + button, I get a message "TypeError: this.props.onQuantityChanged is not a function"

Here's what I have:

Parent class:

import React, { Component } from "react";
import QuantityPicker from "./quantityPicker";

class Product extends Component {
  state = {
    quantity: 1,
  };

  render() {
    return (
       <label>Price Each: $500</label>
       <label>Total Price: ${500 * this.state.quantity}</label>

       <QuantityPicker onQuantityChanged={this.OnQuantityChanged}></QuantityPicker>
    );
  }

  onQuantityChanged = (newQuantity) => {
    this.setState({ quantity: newQuantity });
  };
}
export default Product;

Child Class:

import React, { Component } from "react";

class QuantityPicker extends Component {
  state = {
    quantity: 1,
  };

  render() {
    return (  <button onClick={this.increaseQuantity}>+</button>  );
  }

  increaseQuantity = () => {
    this.setState({ quantity: this.state.quantity + 1 });
    this.props.onQuantityChanged(this.state.quantity);
  };
}
export default QuantityPicker;

Thanks in advance for any insight.

  • 1
    Seems to be an issue with the "this" keyword. You can likely fix it by binding increase quantity in your render function: `increaseQuantity.bind(this)`. Or, better yet, use functional components and these sorts of errors never happen. – ICW May 28 '21 at 00:20

2 Answers2

0

I haven't got a React environment setup to test this at the moment, but I'm pretty sure that your render function isn't going to know what 'this' is. Try turning it into an arrow function, and possibly putting it under the increaseQuantity function.

See : https://stackoverflow.com/a/47417651/4844269

Xaraxia
  • 199
  • 9
0

your problem is the capitalization of your name function

onQuantityChanged not OnQuantityChanged

In your Parent class

<QuantityPicker onQuantityChanged={this.onQuantityChanged}></QuantityPicker>

And the render must contain only one child so use the react fragment

    render() {
        return (
            <>
                <label>Price Each: $500</label>
                <label>Total Price: ${500 * this.state.quantity}</label>

                <QuantityPicker onQuantityChanged={this.onQuantityChanged}></QuantityPicker>
            </>
        );
    }
Daphaz
  • 486
  • 4
  • 7
  • Oh geez. I can't believe I didn't see that, after looking for the proper function calls a hundred times. Thanks, Daphaz! – Todd Mickel May 29 '21 at 15:17