Here is the TypeScript React component that implements the functionality you described:
import React, { useState } from 'react';
import './Input.css';
type InputProps = {
type?: 'text' | 'number';
value?: string | number;
onChange?: (value: string | number) => void;
};
const Input: React.FC<InputProps> = ({ type = 'text', value = '', onChange }) => {
const [isShiftPressed, setIsShiftPressed] = useState(false);
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const inputValue = event.target.value;
const numericValue = parseFloat(inputValue);
if (type === 'number' && !isNaN(numericValue)) {
if (onChange) {
onChange(numericValue);
}
} else if (onChange) {
onChange(inputValue);
}
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Shift') {
setIsShiftPressed(true);
}
};
const handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Shift') {
setIsShiftPressed(false);
}
};
const handleArrowKeyPress = (event: React.KeyboardEvent<HTMLInputElement>, increment: number) => {
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
event.preventDefault();
const newValue =
type === 'number'
? (isShiftPressed ? parseFloat(value as string) + increment * 0.1 : (value as number) + increment)
: value;
if (onChange) {
onChange(newValue);
}
}
};
return (
<input
type={type}
value={value as string}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onKeyPress={(event) => handleArrowKeyPress(event, event.key === 'ArrowUp' ? 1 : -1)}
className="rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
/>
);
};
export default Input;
Here's a brief explanation of the code:
- The
Input component takes a type and value prop, with default values of 'text' and '' respectively.
- The
useState hook is used to track whether the shift key is pressed.
- The
handleInputChange function updates the component's value based on the user's input.
- The
handleKeyDown and handleKeyUp functions track whether the shift key is pressed.
- The
handleArrowKeyPress function increments or decrements the component's value based on the user's arrow key input, with a different increment value if the shift key is pressed.
- The component renders an
input element with various event listeners to handle user input and update the component's value. The component's styles are imported from a separate Input.css file and are implemented using Tailwind CSS.
Note: You will need to import the Tailwind CSS styles in your project for the component to be styled correctly.