Skip to content

useInput

React hook to handle an input element.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useInput
sh
npx @novajslabs/cli add useInput
sh
pnpm dlx @novajslabs/cli add useInput

Or copy and paste the code into your project:

ts
import { useState } from "react";

export const useInput = <T>(initialValue: T) => {
  const [inputValue, setInputValue] = useState(initialValue);

  const onInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(event.target.value as unknown as T);
  };

  return { inputValue, onInputChange };
};
js
import { useState } from "react";

export const useInput = (initialValue) => {
  const [inputValue, setInputValue] = useState(initialValue);

  const onInputChange = (event) => {
    setInputValue(event.target.value);
  };

  return { inputValue, onInputChange };
};

Requirements

React 16.8 or higher

Parameters

initialValue required

Type: any

The initial value of the input element.

Return values

inputValue

Type: any

The current value of the input element.

onInputChange

Type: function

Handles changes to the input element.

Example

tsx
import { useInput } from "./hooks/useInput";

const App = () => {
  const { inputValue: email, onInputChange: emailChange } =
    useInput<string>("");
  const { inputValue: password, onInputChange: passwordChange } =
    useInput<string>("");

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log(email, password);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" value={email} onChange={emailChange} />
      <input type="password" value={password} onChange={passwordChange} />
      <button type="submit">Login</button>
    </form>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Managing form input state and handling user input in a contact form on a website
  • Creating controlled input components for collecting user information in a signup or registration form
  • Implementing dynamic search functionality with input value tracking in a search bar component
  • Developing interactive filtering options for product listings in an e-commerce website
  • Facilitating user interaction in a survey or questionnaire by managing input values

Released under the MIT License.