1

I am attempting to make a button increment an input text value.

The button increments or decrements the value. (value = '+' OR '-')
(See picture below)

To get the value of this input text and then when use the value what we just get and +1

I require a full example of this using reactjs please.

enter image description here

Jim
  • 14,952
  • 15
  • 80
  • 167
Luu Nguyet
  • 19
  • 1
  • 2

1 Answers1

2

Make your input Element to be a controlled one and when you click on buttons you only need to update the state based on which button was clicked

You can read this answer on controlled vs uncontrolled Inputs

Sample Snippet

class App extends React.Component {
 state = {
    count: 0
 }
 
 updateValue = (val) => {
     this.setState(prevState => ({count: prevState.count + val}));
 }
 render() {
    return  <div>
        <input type="number" value={this.state.count} />
        <input type="button" onClick={this.updateValue.bind(this, -1)} value="Decrement"/>
        <input type="button" onClick={this.updateValue.bind(this, 1)} value="Increment"/>
     </div>
 }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.js"></script>
<div id="app"/>
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400