import { ChangeEvent, Component, ReactElement } from 'react'; import { observer } from 'mobx-react'; import classnames from 'classnames'; import { debounce, noop } from 'lodash'; import { mdiCloseCircleOutline, mdiMagnify } from '@mdi/js'; import Icon from './icon'; interface IProps { value?: string; placeholder: string; className?: string; onChange?: (e: string) => void; onReset: () => void; name?: string; throttle?: boolean; throttleDelay?: number; autoFocus?: boolean; } interface IState { value: string; } @observer class SearchInput extends Component { input: HTMLInputElement | null = null; constructor(props: IProps) { super(props); this.state = { value: props.value || '', }; this.throttledOnChange = debounce( this.throttledOnChange, this.props.throttleDelay, ); } componentDidMount(): void { const { autoFocus = false } = this.props; if (autoFocus && this.input) { this.input.focus(); } } onChange(e: ChangeEvent): void { const { throttle = false, onChange = noop } = this.props; const { value } = e.target; this.setState({ value }); if (throttle) { e.persist(); this.throttledOnChange(value); } else { onChange(value); } } throttledOnChange(e: string): void { const { onChange = noop } = this.props; onChange(e); } reset(): void { const { onReset = noop } = this.props; this.setState({ value: '' }); onReset(); } render(): ReactElement { const { className = '', name = 'searchInput', placeholder = '', } = this.props; const { value = '' } = this.state; return (
{/* eslint-disable-next-line jsx-a11y/label-has-associated-control */} {value.length > 0 && ( this.reset()} onKeyDown={noop}> )}
); } } export default SearchInput;