React hook to handle an input element.
Add the hook via the CLI:
npx @novajslabs/cli add useInput
Or copy and paste the code into your project:
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 }
}
React 16.8 or higher
- Name
initialValue
- Type
- any
- Required
- required
- Description
The initial value of the input element.
- Name
inputValue
- Type
- any
- Description
The current value of the input element.
- Name
onInputChange
- Type
- function
- Description
Handles changes to the input element.
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
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