Last active
December 16, 2021 21:27
-
-
Save mitchallen/474766b8c12084c879d3ae27067e4944 to your computer and use it in GitHub Desktop.
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
// File: UseLocalStorageTextInput.tsx | |
// Author: Mitch Allen | |
import {ChangeEventHandler, useCallback, useState} from "react"; | |
export interface LocalStorageTextInput { | |
storageKey?: string, | |
id?: string, | |
name?: string, | |
label?: string, | |
helperText?: string, | |
init?: string, | |
} | |
export interface LocalStorageTextInputProps { | |
id?: string, | |
name?: string, | |
label?: string, | |
value: string, | |
onChange: ChangeEventHandler<HTMLTextAreaElement | HTMLInputElement> | undefined, | |
helperText?: string, | |
} | |
export function useLocalStorageTextInput(options: LocalStorageTextInput = {}): LocalStorageTextInputProps { | |
let { | |
storageKey = undefined, | |
id = undefined, | |
name = undefined, | |
label = 'Text', | |
helperText = undefined, | |
init = '', | |
} = options; | |
if (name === undefined) { | |
name = id; | |
} | |
if( storageKey !== undefined ) { | |
init = localStorage.getItem( storageKey ) || init; | |
} | |
const [value, setValue] = useState(init); | |
const onChange = useCallback((event) => { | |
setValue(event.target.value); | |
if( storageKey ) { | |
localStorage.setItem( storageKey, event.target.value ); | |
} | |
}, [storageKey]); | |
return { | |
id, | |
name, | |
label, | |
value, | |
onChange, | |
helperText, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment