Categories
React Answers

How to create a number input with no negative, decimal, or zero value values with React?

Spread the love

Sometimes, we want to create a number input with no negative, decimal, or zero value values with React.

In this article, we’ll look at how to create a number input with no negative, decimal, or zero value values with React.

How to create a number input with no negative, decimal, or zero value values with React?

To create a number input with no negative, decimal, or zero value values with React, we can create our own input component.

For instance, we write:

import React, { useState } from "react";

const PositiveInput = () => {
  const [value, setValue] = useState("");

  const onChange = (e) => {
    const value = e.target.value.replace(/[^\d]/, "");

    if (+value !== 0) {
      setValue(value);
    }
  };

  return <input type="text" value={value} onChange={onChange} />;
};

export default function App() {
  return (
    <>
      <PositiveInput />
    </>
  );
}

We create the PositiveInput component that lets us only enter positive numbers.

In the component, we have the value state.

And we define the onChange function that sets the value state by getting the value from the input.

And we replace all the non numerical values in the input value with empty strings.

This is done with const value = e.target.value.replace(/[^\d]/, "");.

Then if value isn’t 0, then we call setValue to set value.

Next, we set the value prop of the input to value and the onChange prop to onChange.

Finally, we add the input to App.

Conclusion

To create a number input with no negative, decimal, or zero value values with React, we can create our own input component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to create a number input with no negative, decimal, or zero value values with React?”

how do i use this as a separate component because then onChange will be override from outside and internal onchange will no longer work.

Leave a Reply

Your email address will not be published. Required fields are marked *