Last active
August 17, 2020 12:57
-
-
Save themgoncalves/6473e5335bc03f2ad05a07e8ce3660cf to your computer and use it in GitHub Desktop.
Working with multiple references on React - Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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