Home > Enterprise >  Correct way to setup a class variable for total QTY of product to be altered by buttons (React JS)
Correct way to setup a class variable for total QTY of product to be altered by buttons (React JS)

Time:02-14

I am building a product detail page and created a class app to contain the main code of the project to facilitate a constructor for loading data from my API.

I want to have 3 numeric variables which I can increase/decrease via buttons on page It set for 3 products of QHD, HD, Batteries.

I wrote the following code but its not correct and I am searching for correct ways to implement this.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
      HD: 0,
    };
  }

  componentDidMount() {
    fetch("https://fe-assignment.vaimo.net/")
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        this.setState({
          isLoaded: true,
          items: data,
          TI: 0,
        });
      });
  }

  increaseHD() {
    HD = 1;
  }

Continued

render() {
    const HD = 0;
<div className="button-row">
                    <button className="minus">-</button>
                    <form className="input">{HD}</form>
                    <button className="plus" onClick={this.increaseHD}> </button>
                  </div>
    

Returns the error that this undefined. I know it should be setup up perhaps in the constructor or class wide as but I am new to reactjs and need some help

CodePudding user response:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
      HD: 0,
    }
  }

  increaseHD = () => {
    this.setState({
      HD: 5
    })
  }
  

  render() {
    
    return (
     <div>
       Hello {this.state.HD} 
       <button className="plus" onClick={this.increaseHD}> </button>
      </div>
    )
  }
}

You can also increase hd by taking in prev state of the component

increaseHD = () => {
    this.setState({
      HD: this.state.HD   1
    })
  }
  • Related