react#InputHTMLAttributes TypeScript Examples
The following examples show how to use
react#InputHTMLAttributes.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomInput.tsx From typed-react-form with MIT License | 6 votes |
// Basic example of a type-checked input, which you can pass <input> props to.
// Make sure to add Omit, otherwise our form and name props will interfere
function CustomInput2<T extends object>(props: { form: FormState<T>; name: keyof T } & Omit<InputHTMLAttributes<HTMLInputElement>, "form" | "name">) {
// Rest contains <input> props
const { form, name, ...rest } = props;
const { value, setValue } = useListener(form, name);
// Apply <input> props using {...rest}
return <input value={value + ""} onChange={(ev) => setValue(ev.target.value as any)} {...rest} />;
}
Example #2
Source File: CustomInput.tsx From typed-react-form with MIT License | 6 votes |
// Fully fledged type-checked input
function CustomInput6<T extends object, Key extends keyof T>(
props: { form: FormState<T>; name: Key } & SerializeProps<T[Key]> &
Omit<InputHTMLAttributes<HTMLInputElement>, "form" | "name" | "value" | "type">
) {
// Remove SerializeProps, form and name from props so rest contains the <input> props.
const { form, name, dateAsNumber, setNullOnUncheck, setUndefinedOnUncheck, value: inputValue, type, ...rest } = props;
const { value, setValue } = useListener(form, name);
let v = defaultSerializer(value, { dateAsNumber, setNullOnUncheck, setUndefinedOnUncheck, value: inputValue, type });
return (
<input
type={type}
value={typeof v === "string" ? v : undefined}
checked={typeof v === "boolean" ? v : undefined}
onChange={(ev) => setValue(defaultDeserializer(ev.target.value ?? ev.target.checked, value, props))}
{...rest}
/>
);
}
Example #3
Source File: FileInput.tsx From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
FileInput = (props: InputHTMLAttributes<HTMLInputElement>) => (
<div className="usa-file-input">
<div className="usa-file-input__target">
<div className="usa-file-input__instructions" aria-hidden="true">
<span className="usa-file-input__choose">Choose a file</span>
</div>
<div className="usa-file-input__box"></div>
<input className="usa-file-input__input" type="file" {...props} />
</div>
</div>
)
Example #4
Source File: atoms.tsx From jeffjadulco.com with MIT License | 6 votes |
Input = ({
labelText,
name,
...props
}: { labelText: string } & InputHTMLAttributes<HTMLInputElement>) => {
return (
<div className="group">
<label
className="text-sm font-medium transition-colors duration-200 text-fore-secondary group-hover:text-accent"
htmlFor={name}
>
{labelText}
</label>
<input
className="block w-full p-3 mt-1 border rounded-md outline-none border-back-subtle bg-back-primary focus:border-accent text-primary disabled:opacity-50"
name={name}
{...props}
/>
</div>
)
}
Example #5
Source File: Inputs.tsx From crosshare with GNU Affero General Public License v3.0 | 6 votes |
LengthLimitedInput = ({
maxLength,
updateValue,
...props
}: LengthLimitedProps &
DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>) => {
return (
<input
{...props}
onChange={(e) => updateValue(e.target.value.substring(0, maxLength))}
/>
);
}
Example #6
Source File: useTextField.ts From use-platform with MIT License | 6 votes |
export function useTextField<T extends HTMLInputElement | HTMLTextAreaElement>(
props: CommonTextFieldProps,
inputRef: RefObject<T>,
): T extends HTMLTextAreaElement
? UseTextFieldResult<TextareaHTMLAttributes<T>>
: UseTextFieldResult<InputHTMLAttributes<T>> {
const { as: elementType = 'input', type = 'text', autoComplete = 'off', ...restProps } = props
const { focusableProps } = useFocusable(props, inputRef)
let additionalProps: InputHTMLAttributes<HTMLInputElement> = {}
if (elementType === 'input') {
additionalProps = { type }
}
useLayoutEffect(() => {
// By default autofocus set cursor at start position when element type is textarea.
if (elementType === 'textarea') {
setCursorToEnd(inputRef.current)
}
}, [elementType, inputRef, props.autoFocus])
return {
inputProps: {
autoComplete,
...restProps,
...focusableProps,
...additionalProps,
},
} as any
}
Example #7
Source File: index.tsx From admin with MIT License | 5 votes |
GeneratingInput = React.forwardRef(
(
{
placeholder,
label,
name,
required,
deletable,
onDelete,
onChange,
onFocus,
tooltipContent,
tooltip,
props,
className,
value: valueProp,
...fieldProps
}: Omit<InputProps, "prefix" | "key">,
ref
) => {
const [value, setValue] = useState<
InputHTMLAttributes<HTMLInputElement>["value"]
>(valueProp || "")
const inputRef = useRef<HTMLInputElement>(null)
useImperativeHandle(ref, () => inputRef.current)
const generateCode = () => {
setValue(generatePromotionCode())
}
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value)
if (onChange) {
onChange(e)
}
}
return (
<InputContainer
className={className}
key={name}
onClick={() => !fieldProps.disabled && inputRef?.current?.focus()}
{...props}
>
<div className="flex">
<InputHeader {...{ label, required, tooltipContent, tooltip }} />
{!value && (
<button
onClick={generateCode}
className="inter-small-semibold text-violet-50"
>
Generate
</button>
)}
</div>
<div className="flex">
<input
ref={inputRef}
value={value}
onChange={handleChange}
className="bg-inherit outline-none outline-0 w-full remove-number-spinner leading-base text-grey-90 font-normal caret-violet-60 placeholder-grey-40"
placeholder={placeholder}
autoComplete="off"
name={name}
onFocus={onFocus}
required={required}
{...fieldProps}
/>
{value && (
<button onClick={generateCode}>
<RefreshIcon size={16} className="text-grey-50" />
</button>
)}
</div>
</InputContainer>
)
}
)
Example #8
Source File: default.tsx From use-platform with MIT License | 5 votes |
Input: FC<InputHTMLAttributes<HTMLInputElement>> = (props) => {
const [isFocused, onFocusChange] = useState(false)
const { focusProps } = useFocus({ ...props, onFocusChange })
return <input className={classNames.input} {...props} {...focusProps} data-focused={isFocused} />
}
Example #9
Source File: FeInput.tsx From frontegg-react with MIT License | 4 votes |
FeInput = forwardRef<HTMLInputElement, InputProps>((props, forwardRef) => {
const {
size,
label,
error,
inForm,
variant,
className,
multiline,
fullWidth,
prefixIcon,
suffixIcon,
labelButton,
onSearch: propsOnSearch,
type: propsType = 'text',
...restProps
} = props;
const { iconAction, ...propsWithoutJunk } = restProps;
const [showPassword, setShowPassword] = useState(false);
const togglePassword = useCallback(() => setShowPassword((_) => !_), []);
const [text, setText] = useState(props.value);
const changeText = useCallback((e: ChangeEvent<HTMLInputElement>) => setText(e.target.value), []);
const onSearch = useCallback(() => propsOnSearch?.(text as string), [text]);
const withPrefixIcon = !!prefixIcon;
const withSuffixIcon = propsType === 'password' || propsType === 'search' || !!suffixIcon;
const classes = ClassNameGenerator.generate(
{
prefixCls,
className,
isFullWidth: fullWidth,
},
inForm && 'in-form',
withPrefixIcon && `with-prefix-icon`,
withSuffixIcon && `with-suffix-icon`
);
const innerClasses = ClassNameGenerator.generate(
{
prefixCls: `${prefixCls}__inner`,
className,
size,
theme: props.disabled ? 'disabled' : variant,
},
multiline && 'multi',
error && 'error'
);
const clickableIconClasses = ClassNameGenerator.generate({
prefixCls: 'fe-icon',
isClickable: true,
});
const element = multiline ? 'textarea' : 'input';
const type = propsType === 'password' && showPassword ? 'text' : propsType === 'search' ? 'text' : propsType;
return (
<div className={classes}>
{(label || labelButton) && (
<div className={`${prefixCls}__header`}>
{label && <div className={`${prefixCls}__label`}>{label}</div>}
{labelButton && (
<FeButton
tabIndex={-1}
className={classNames(`${prefixCls}__label-button`, labelButton.className)}
{...labelButton}
/>
)}
</div>
)}
<div className={innerClasses}>
{prefixIcon}
{React.createElement<InputHTMLAttributes<HTMLInputElement> | TextareaHTMLAttributes<HTMLTextAreaElement>>(
element,
{
...propsWithoutJunk,
className: `${prefixCls}__input`,
value: props.hasOwnProperty('value') ? props.value : text,
onChange: props.onChange || changeText,
type,
ref: forwardRef,
} as any
)}
{propsType === 'password' && (
<FeIcon
className={clickableIconClasses}
name={showPassword ? 'visibility' : 'visibility-off'}
onClick={togglePassword}
/>
)}
{propsType === 'search' && <FeIcon className={clickableIconClasses} name='search' onClick={onSearch} />}
{suffixIcon}
</div>
{error && <div className={`${prefixCls}__error`}>{error}</div>}
</div>
);
})
Example #10
Source File: TagInput.tsx From Hybooru with MIT License | 4 votes |
export default function TagInput({ ...rest }: InputHTMLAttributes<HTMLInputElement>) {
const [showNamespace] = useLocalStorage("namespaces", false);
const [tags, setTags] = useState<Record<string, number> | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
const tagsRef = useRef<HTMLDivElement | null>(null);
const box = inputRef.current?.getBoundingClientRect();
const timeoutRef = useRef<NodeJS.Timeout | number | null>(null);
const blurRef = useRef<NodeJS.Timeout | number | null>(null);
const requestRef = useRef<Canceler | null>(null);
const [query, setQuery] = useRTQuery();
const queryRef = useRef(query);
queryRef.current = query;
const stop = useCallback(() => {
if(timeoutRef.current) {
clearTimeout(timeoutRef.current as any);
timeoutRef.current = null;
}
if(requestRef.current) {
requestRef.current();
requestRef.current = null;
}
}, []);
const reset = useCallback(() => {
stop();
timeoutRef.current = setTimeout(async () => {
timeoutRef.current = null;
let query = queryRef.current.split(" ").slice(-1)[0];
if(query.startsWith("-")) query = query.slice(1);
query = `*${query}*`;
const result = await requestJSON<TagsSearchResponse, TagsSearchRequest>({
pathname: "/api/tags",
search: {
pageSize: TAGS_COUNT,
query,
},
cancelCb: cancel => requestRef.current = cancel,
});
setTags(result.tags);
}, DEBOUNCE_FREQ);
}, [stop]);
const onFocus = useCallback(() => {
reset();
if(blurRef.current) clearTimeout(blurRef.current as any);
}, [reset]);
const onBlur = useCallback(() => {
blurRef.current = setTimeout(() => {
blurRef.current = null;
setTags(null);
stop();
}, 100);
}, [stop]);
const onInputChange = useCallback((ev: React.ChangeEvent<HTMLInputElement>) => {
reset();
setQuery(ev.target.value, true);
}, [reset, setQuery]);
const onRowClick = useCallback((tag: string) => {
setQuery(query => {
inputRef.current?.focus();
const parts = query.split(" ");
if(parts[parts.length - 1].startsWith("-")) tag = `-${tag}`;
parts[parts.length - 1] = tag;
return parts.join(" ") + " ";
}, true);
}, [setQuery]);
const onKeyPress = useCallback((ev: React.KeyboardEvent<HTMLInputElement>) => {
if(ev.key === "Enter") {
ev.currentTarget.blur();
}
}, []);
const onKeyDown = useCallback((ev: React.KeyboardEvent<HTMLInputElement>) => {
if(ev.key === "ArrowDown" || ev.key === "ArrowUp") {
ev.preventDefault();
const targets = [inputRef.current, ...Array.from(tagsRef.current?.children || [])] as Array<(null | HTMLAnchorElement | HTMLInputElement)>;
const cur = targets.indexOf(document.activeElement as any);
if(cur < 0) return;
const dir = ev.key === "ArrowDown" ? 1 : -1;
targets[cur + dir]?.focus();
}
}, []);
return (
<span className="TagInput" onFocus={onFocus} onBlur={onBlur} onKeyDown={onKeyDown}>
<input value={query} {...rest} ref={inputRef}
autoComplete="off" autoCorrect="off"
onChange={onInputChange} onKeyPress={onKeyPress} />
{tags && box &&
<div className="tags" ref={tagsRef}
style={{
left: `${box.x - 1}px`,
top: `${box.y + box.height - 1}px`,
width: `${box.width + 2}px`,
}}>
{Object.entries(tags).map(([tag, posts]) => <Row key={tag} tag={tag} posts={posts} onClick={onRowClick} showNamespace={showNamespace} />)}
</div>
}
</span>
);
}