0

I created a increment/decrement function, but I have a doubt.

I can decrement count clicking in same button that include a increment count? How to create that function?

Code:

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      clicks: 0,
      show: true
    };
  }

  IncrementItem = () => {
    this.setState({ clicks: this.state.clicks + 1 });
  }
  DecreaseItem = () => {
    this.setState({ clicks: this.state.clicks - 1 });
  }
  ToggleClick = () => {
    this.setState({ show: !this.state.show });
  }

  render() {
    return (
      <div>
        <button onClick={this.IncrementItem}>Click to increment by 1</button>
        <button onClick={this.DecreaseItem}>Click to decrease by 1</button>
        <button onClick={this.ToggleClick}>
          { this.state.show ? 'Hide number' : 'Show number' }
        </button>
        { this.state.show ? <h2>{ this.state.clicks }</h2> : '' }
      </div>
    );
  }
}

export default App;
6
  • 1
    Hi, can you more clearly explain what it is you are trying to do, or what you want to do, or what might not be working as expected? It's very unclear what you are asking. Commented May 3, 2020 at 20:49
  • yeah, ok. For example: a like button on instagram. as soon as i click on the button it adds a like and when i click on that same like button this like is removed. Commented May 3, 2020 at 20:54
  • So... basically a toggle? A boolean state?.....there's some global state count and you want a single button to either add +1 if enabled, +0 if not? Commented May 3, 2020 at 20:56
  • yes, I'm trying to do it this way! Commented May 3, 2020 at 20:59
  • Check how to increase decrease count on click of same button in React Commented May 3, 2020 at 21:04

1 Answer 1

0

You could set a conditional in the function you trigger when you click on the button. Maybe something like this:

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
      clicked: false,
    };
  }

  toggleClicked = () => {
      const counter = this.state.clicked ? counter +1 : counter - 1;
      const clicked = !this.state.clicked;

      this.setState({ counter, clicked })
  }

  render() {
    return (
      <div>
        <button onClick={this.toggleClicked}>Click</button>

        { this.state.counter ? <h2>{ this.state.counter }</h2> : '' }
      </div>
    );
  }
}

export default App;

This way if you have already clicked the counter will decrease by 1 and viceversa.

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.