1
0
Fork 0
mirror of https://github.com/pawelmalak/flame.git synced 2025-08-03 18:05:18 +02:00
flame/client/src/components/SearchBar/SearchBar.tsx

56 lines
1.3 KiB
TypeScript
Raw Normal View History

import { useRef, useEffect, KeyboardEvent } from 'react';
// Redux
import { connect } from 'react-redux';
import { createNotification } from '../../store/actions';
// Typescript
import { NewNotification } from '../../interfaces';
// CSS
import classes from './SearchBar.module.css';
// Utils
import { searchParser } from '../../utility';
interface ComponentProps {
createNotification: (notification: NewNotification) => void;
2021-09-06 12:24:01 +02:00
setLocalSearch: (query: string) => void;
}
const SearchBar = (props: ComponentProps): JSX.Element => {
2021-09-06 12:24:01 +02:00
const { setLocalSearch, createNotification } = props;
const inputRef = useRef<HTMLInputElement>(document.createElement('input'));
useEffect(() => {
inputRef.current.focus();
2021-09-06 12:24:01 +02:00
}, []);
const searchHandler = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.code === 'Enter') {
2021-09-06 12:24:01 +02:00
const searchResult = searchParser(inputRef.current.value);
2021-09-06 12:24:01 +02:00
if (!searchResult.prefix) {
createNotification({
title: 'Error',
2021-09-06 12:24:01 +02:00
message: 'Prefix not found',
});
} else if (searchResult.isLocal) {
setLocalSearch(searchResult.query);
}
}
2021-09-06 12:24:01 +02:00
};
return (
<input
ref={inputRef}
2021-09-06 12:24:01 +02:00
type="text"
className={classes.SearchBar}
onKeyDown={(e) => searchHandler(e)}
/>
2021-09-06 12:24:01 +02:00
);
};
2021-09-06 12:24:01 +02:00
export default connect(null, { createNotification })(SearchBar);