K.Z
K.Z

Reputation: 5075

In react component, Cannot clear last integer from input box using back space

I have react component in which I have input 'TextBoxSearch' which only accept the integer number. My following code works fine but cannot clear last integer from the input. for example if I type 234, I can clear 4 3 but not 2.

const handleChangeSiteId = (siteId)=>{
const re = /^[0-9\b]+$/;

if (site === '' || re.test(siteId)) {
   setSiteForTransactionsModal(siteId);
  }
}


<TextBoxSearch
    placeholder= "SiteId"
    buttonColor="primary"
    buttonMessage="Transactions Summary"
    handleChange={handleChangeSiteId}
    handleSearch={handleTransactionsSummarySearch}
    value={site}
 ></TextBoxSearch>

Upvotes: 0

Views: 26

Answers (1)

Shubham Verma
Shubham Verma

Reputation: 5054

I have tried this POC. Ideally in your case it would be like this:

const handleChangeSiteId = (siteId)=>{
const re = /^[0-9\b]+$/;

if (siteId === '' || re.test(siteId)) { //check here
   setSiteForTransactionsModal(siteId);
  }

Here is my POC for same thing:

import {useState} from 'react';

import "./styles.css";

export default function App() {
  const [site,setSiteForTransactionsModal] = useState('');
  const handleChangeSiteId = (e)=>{
    console.log(e.target.value,site)
    const re = /^[0-9\b]+$/;
    
    if (e.target.value === '' || re.test(e.target.value)) {
       setSiteForTransactionsModal(e.target.value);
      }
    }
    
    
    
  return (
    <div className="App">
      <input 
      placeholder= "SiteId"
        buttonColor="primary"
        buttonMessage="Transactions Summary"
        onChange={handleChangeSiteId}
        // handleSearch={handleTransactionsSummarySearch}
        value={site} />
    </div>
  );
}

Here is the demo url: https://codesandbox.io/s/icy-microservice-glczv?file=/src/App.js:0-688

Upvotes: 2

Related Questions