Pavindu
Pavindu

Reputation: 3123

How to stop an event from being further processed in React

I have a text input in my React app which I don't want to take inputs which are greater than 100. For example, If the entered value is 105, an alert is created and the event is terminated i.e changing input value is not gonna happen. Now I couldn't find a way to do this inside onChange function. Any help would be highly appreciated.

<input onChange={handleChange} name="t"/>

handleChange = e => {
  if(e.target.value > 100){
    alert("High")
    //Here I want to stop event so that changing text in the input doesn't happen
  }
} 

Upvotes: 0

Views: 1007

Answers (3)

Magelan
Magelan

Reputation: 189

handleChange = e => {
  if(e.target.value > 100){
    alert("High");
    e.target.value = "";
  }
  else {
    // your normal processing
  }
} 

should work.

Explanation: Your code would simply not be executed in case the if condition is true. The line e.target.value = "" doesn't actually "not show" the users input (as asked for in comment), but rather overrides it with empty string.

Mention: This solution has nothing to do with React, but rather works in any context.

Upvotes: 0

marzelin
marzelin

Reputation: 11610

Make it a controlled input and only set the value if a condition is met.

const App = () => {
  const [value, setValue] = React.useState("");
  const handler = (e) => {
    const value = Number(e.target.value);
    value <= 100 && setValue(value);
  };
  return (
    <input onInput={handler} type="number" value={value} />
  );
}


ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 0

Jay Kariesch
Jay Kariesch

Reputation: 1482

If I'm understanding you properly, if a specific condition is not met, you want to prevent the input from reflecting the text the user just entered.

In order to accomplish this, you'll need to control your input's value via state.

That means doing something like this:

<input onChange={handleChange} name="t" value={this.state.tInput}/>

handleChange = e => {
  if(parseInt(e.target.value) > 100) {

    alert("High")
    // set input state here to previous value to re-render and remove unwanted input values from input
    return this.setState(({tInput}) => ({tInput}))
  }
  return this.setState({tInput: e.target.value})
} 

Upvotes: 0

Related Questions