Hirokita
Hirokita

Reputation: 11

How to let the user input number and increase it with a button in React JS

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;

Upvotes: 0

Views: 9573

Answers (3)

Reed Dunkle
Reed Dunkle

Reputation: 3597

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>
  );
}

Upvotes: 0

JordyJordyJordyJordan
JordyJordyJordyJordan

Reputation: 147

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>
  )
}

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 282130

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

Upvotes: 1

Related Questions