fix(striker-ui): change InputWithRef to accept any input element as base

main
Tsu-ba-me 2 years ago
parent cbad0ebf5e
commit 96fd7f739e
  1. 28
      striker-ui/components/InputWithRef.tsx

@ -1,12 +1,16 @@
import { ForwardedRef, forwardRef, useImperativeHandle, useState } from 'react'; import {
cloneElement,
ForwardedRef,
forwardRef,
ReactElement,
useImperativeHandle,
useState,
} from 'react';
import createInputOnChangeHandler, { import createInputOnChangeHandler, {
CreateInputOnChangeHandlerOptions, CreateInputOnChangeHandlerOptions,
MapToStateSetter, MapToStateSetter,
} from '../lib/createInputOnChangeHandler'; } from '../lib/createInputOnChangeHandler';
import OutlinedInputWithLabel, {
OutlinedInputWithLabelProps,
} from './OutlinedInputWithLabel';
type InputWithRefOptionalProps<TypeName extends keyof MapToType> = { type InputWithRefOptionalProps<TypeName extends keyof MapToType> = {
createInputOnChangeHandlerOptions?: Omit< createInputOnChangeHandlerOptions?: Omit<
@ -16,8 +20,12 @@ type InputWithRefOptionalProps<TypeName extends keyof MapToType> = {
valueType?: TypeName | 'string'; valueType?: TypeName | 'string';
}; };
type InputWithRefProps<TypeName extends keyof MapToType> = type InputWithRefProps<
OutlinedInputWithLabelProps & InputWithRefOptionalProps<TypeName>; TypeName extends keyof MapToType,
InputComponent extends ReactElement,
> = InputWithRefOptionalProps<TypeName> & {
input: InputComponent;
};
type InputForwardedRefContent<TypeName extends keyof MapToType> = { type InputForwardedRefContent<TypeName extends keyof MapToType> = {
isChangedByUser?: boolean; isChangedByUser?: boolean;
@ -38,15 +46,15 @@ const INPUT_WITH_REF_DEFAULT_PROPS: Required<
}; };
const InputWithRef = forwardRef( const InputWithRef = forwardRef(
<TypeName extends keyof MapToType>( <TypeName extends keyof MapToType, InputComponent extends ReactElement>(
{ {
createInputOnChangeHandlerOptions: { createInputOnChangeHandlerOptions: {
postSet: postSetAppend, postSet: postSetAppend,
...restCreateInputOnChangeHandlerOptions ...restCreateInputOnChangeHandlerOptions
} = INPUT_WITH_REF_DEFAULT_PROPS.createInputOnChangeHandlerOptions, } = INPUT_WITH_REF_DEFAULT_PROPS.createInputOnChangeHandlerOptions,
input,
valueType = INPUT_WITH_REF_DEFAULT_PROPS.valueType, valueType = INPUT_WITH_REF_DEFAULT_PROPS.valueType,
...restProps }: InputWithRefProps<TypeName, InputComponent>,
}: InputWithRefProps<TypeName>,
ref: ForwardedRef<InputForwardedRefContent<TypeName>>, ref: ForwardedRef<InputForwardedRefContent<TypeName>>,
) => { ) => {
const [value, setValue] = useState<MapToType[TypeName]>( const [value, setValue] = useState<MapToType[TypeName]>(
@ -74,7 +82,7 @@ const InputWithRef = forwardRef(
[isChangedByUser, value], [isChangedByUser, value],
); );
return <OutlinedInputWithLabel {...{ onChange, value, ...restProps }} />; return cloneElement(input, { ...input.props, onChange, value });
}, },
); );

Loading…
Cancel
Save