How to empty a text box by using a button in react?

My problem is straightforward I have a text box to input numbers, and after pressing the button, I want to clear the text box value. I have no idea how to do it, and can anybody help me?


Example: When I press the add button in the Chairs row, 10 should be cleared.

                            <CCol className="col-sm-6">
                                onChange={(e) => {
                                  quantity[index] =
                                onClick={() => {
                                  handleSave(item._id, index)
                                <CIcon icon={cilPlus} className="me-2" />

>Solution :

You should define a state for the quantity and then update that state whenever the user enters a new value to that new value. Or when the Clear button is pressed update it to 0.

You could of course also update to an empty string if you want. You would then just need to be careful with the types as + means string concatenation if a string is involved, not addition. So make sure your program handles that correctly.

function App() {
  const [quantity, setQuantity] = React.useState(0);

  return (
      <input value={quantity} type="number" onChange={e => setQuantity(} />
      <button onClick={() => setQuantity(0)}>Clear</button>

ReactDOM.render(<App/>, document.getElementById('root'));
<script src=""></script>
<script src=""></script>
<div id="root"></div>

Also it seems you are using an array as for all quantities which is perfectly fine, just make sure that you create a new array when you update a quantity as state should be treated as immutable in React and a state update is only triggered when the reference of the array changes as only a shallow comparison is done. You could do that e.g. like this. This thread might also be helpful in that regard.

// original
const quantities = [3, 12, 24];
// index to update the array on
const index = 1;
// create a new array with the quantity at index increased by 1
const newQuantities = [...quantities.slice(0, index), quantities[index] + 1, ...quantities.slice(index + 1)];

// arrays are actually two different arrays
// references are not the same
console.log(quantities === newQuantities);

Leave a Reply