Skip to content

Instantly share code, notes, and snippets.

@themgoncalves
Last active August 17, 2020 12:57
Show Gist options
  • Save themgoncalves/6473e5335bc03f2ad05a07e8ce3660cf to your computer and use it in GitHub Desktop.
Save themgoncalves/6473e5335bc03f2ad05a07e8ce3660cf to your computer and use it in GitHub Desktop.
Working with multiple references on React - Demo
import React from 'react';
import mergeRefs from './typescript-merge-refs.ts';
export interface InputElement extends ICSSCustom, Partial<HTMLInputElement> {
readonly?: boolean;
disabled?: boolean;
onChange: (value: string) => void;
}
export const Input = React.forwardRef<HTMLInputElement, InputElement>((props: InputElement, ref) => {
const {
disabled,
readonly,
onChange,
...rest
} = props;
const [value, updateValue] = React.useState<string>();
const localRef = React.useRef<HTMLDivElement>();
const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
const {
target: { value: inputValue },
} = event;
onChange(inputValue);
updateValue(inputValue);
};
console.log('localRef', localRef); // output element ref
return (
<input
type="text"
value={value}
onChange={handleOnChange}
disabled={disabled}
readOnly={readonly}
{...rest}
ref={mergeRefs<HTMLDivElement>(ref, testRef)}
/>
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment