0

I want to let the user input the clicks times and increase it with a button, but I don't know-how. Here's the code.

import React, { Component } from "react";

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


  IncrementItem = () => {
    this.setState({ clicks: this.state.clicks + 1 });
  };

  DecreaseItem = () => {
    if (this.state.clicks < 1) {
      this.setState({
        clicks: 0,
      });
    } else {
      this.setState({
        clicks: this.state.clicks - 1,
      });
    }
  };
  ToggleClick = () => {
    this.setState({ show: !this.state.show });
  };
  handleChange(event) {
    this.setState({ clicks: event.target.value });
  }

  render() {
    return (
      <div>
        <button onClick={this.DecreaseItem}>Click to decrease by 1</button>
        <button onClick={this.IncrementItem}>Click to increase by 1</button>

        <button onClick={this.ToggleClick}>
          {this.state.show ? "Hide number" : "Show number"}
        </button>
        {this.state.show ? ( <input type="number" name="clicks" value={this.state.clicks}onChange = {this.handleChange.bind(this)}/>) : (" ")}
      </div>
    );
  }
}

export default Click;

3 Answers 3

2

You need to convert the event.target.value to number before saving it in state otherwise its just saved as a string

  handleChange(event) {
    this.setState({ clicks: Number(event.target.value) });
  }

Also replace the input value field to value={Number(this.state.clicks).toString()} so that it doesn't keep on showing the leading 0

Working demo

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

2 Comments

This works well, but I can't remove the 0 after I changed the code. Is there any way to remove the 0 and then input the number in?
Updated my answer
1

The other answer doesn't account for min and max values. Here's my approach (I'm using this for an RSVP form, hence the guest constants)

import React, { useState } from 'react'

export default function RSVP() {
  const [count, setCount] = useState(1)
  const maxGuests = 10
  const minGuests = 1

  const handleCount = (e) => {
    if (e > maxGuests) {
      setCount(maxGuests)
    } else if (e < minGuests) {
      setCount(minGuests)
    } else setCount(e)
  }

  const decrementCount = () => {
    if (count > minGuests) setCount(count - 1)
  }

  const incrementCount = () => {
    if (count < maxGuests) setCount(count + 1)
    else if (count > maxGuests) setCount(maxGuests)
  }

  return (
    <form>
      <div className='flex gap-3 py-4 my-3'>
        <input
          type='button'
          onClick={() => decrementCount()}
          value='-'
          className='cursor-pointer'
        />
        <input
          required
          type='number'
          name='counter'
          value={count}
          onChange={(event) => {
            handleCount(event.target.value)
          }}
        />
        <input
          type='button'
          onClick={() => incrementCount()}
          value='+'
          className='cursor-pointer'
        />
      </div>
    </form>
  )
}

Comments

0

In case it helps someone, here's an example using a function components, using React Hooks.

Edit react-component-state-example

import React, { useState } from "react";

function Click() {
  const [count, setCount] = useState(0);
  const [isVisible, setIsVisible] = useState(true);

  const decrementCount = () => {
    if (count > 0) setCount(count - 1);
  };

  const incrementCount = () => {
    setCount(count + 1);
  };

  const toggleVisibility = () => {
    setIsVisible(!isVisible);
  };

  return (
    <div>
      <button onClick={decrementCount}>Click to decrease by 1</button>
      <button onClick={incrementCount}>Click to increase by 1</button>
      <button onClick={toggleVisibility}>
        {isVisible ? "Hide number" : "Show number"}
      </button>
      {isVisible && (
        <input
          type="number"
          name="clicks"
          value={count}
          onChange={(event) => {
            const value = Number(event.target.value);
            setCount(value);
          }}
        />
      )}
    </div>
  );
}

3 Comments

This does not work if you manually input a number and then attempt to use in increment buttons- it pushes the new number to the end. If you manually enter 5 and then hit the +1 button, the number changes to 51.
If you have a min and max**
@JordyJordyJordyJordan Good catch. I think I fixed it by casting the value of the input to a Number() before storing it in state. It's been a few years since I've used CodeSandbox so I'm not 100% if the change saved.

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.