Skip to content

Commit

Permalink
Move handling of input length to useInputProps hook
Browse files Browse the repository at this point in the history
  • Loading branch information
cgero-eth committed Dec 11, 2023
1 parent c77589d commit 779910e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
13 changes: 2 additions & 11 deletions src/components/input/inputText/inputText.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,14 @@
import { useState, type ChangeEvent } from 'react';
import { InputContainer, type IInputComponentProps } from '../inputContainer';
import { useInputProps } from '../useInputProps';

export interface IInputTextProps extends IInputComponentProps {}

export const InputText: React.FC<IInputTextProps> = (props) => {
const { containerProps, inputProps } = useInputProps(props);
const { value, onChange, ...otherInputProps } = inputProps;

const [inputLength, setInputLength] = useState(0);

const handleOnChange = (event: ChangeEvent<HTMLInputElement>) => {
setInputLength(event.target.value.length);
onChange?.(event);
};

return (
<InputContainer inputLength={inputLength} {...containerProps}>
<input type="text" value={value} onChange={handleOnChange} {...otherInputProps} />
<InputContainer {...containerProps}>
<input type="text" {...inputProps} />
</InputContainer>
);
};
14 changes: 13 additions & 1 deletion src/components/input/useInputProps.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import classNames from 'classnames';
import { useId, type InputHTMLAttributes } from 'react';
import { useId, useState, type ChangeEvent, type InputHTMLAttributes } from 'react';
import type { IInputComponentProps, IInputContainerProps } from './inputContainer';

export interface IUseInputPropsResult {
Expand Down Expand Up @@ -30,12 +30,22 @@ export const useInputProps = (props: IInputComponentProps): IUseInputPropsResult
id,
className,
maxLength,
onChange,
...inputElementProps
} = props;

// Set a random generated id to the input field when id property is not defined to properly link the
// input with the label
const randomId = useId();
const processedId = id ?? randomId;

const [inputLength, setInputLength] = useState(0);

const handleOnChange = (event: ChangeEvent<HTMLInputElement>) => {
setInputLength(event.target.value.length);
onChange?.(event);
};

const containerProps = {
label,
variant,
Expand All @@ -46,6 +56,7 @@ export const useInputProps = (props: IInputComponentProps): IUseInputPropsResult
id: processedId,
maxLength,
className,
inputLength,
};

const inputClasses = classNames(
Expand All @@ -58,6 +69,7 @@ export const useInputProps = (props: IInputComponentProps): IUseInputPropsResult
id: processedId,
disabled: isDisabled,
className: inputClasses,
onChange: handleOnChange,
maxLength,
...inputElementProps,
};
Expand Down

0 comments on commit 779910e

Please sign in to comment.