-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchForm.tsx
106 lines (93 loc) · 1.97 KB
/
SearchForm.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { ComponentProps, FC, FormEvent, useReducer } from 'react'
import { Form, Button } from 'react-bootstrap'
import styled from 'styled-components'
import { SearchFormProvider } from './searchFormContext'
import reducer, { CLEAR_FIELD, RESET, SET_FIELD } from './reducer'
const Container = styled(Form)`
margin: 20px;
padding: 16px;
border-radius: 8px;
box-shadow: 0 0 10px 2px #0000000f;
`
const Fields = styled.div`
display: flex;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 16px;
`
const Buttons = styled.div`
display: flex;
gap: 8px;
`
interface SearchFormProps extends ComponentProps<typeof Form> {
onSearch: (fields: Record<string, any>) => void
onClear?: () => void
}
const SearchForm: FC<SearchFormProps> = ({
onSearch,
onClear,
children,
...restProps
}) => {
const [fields, dispatch] = useReducer(reducer, {})
const setFieldValue = ({
fieldKey,
value
}: {
fieldKey: string
value: any
}) => {
dispatch({
type: SET_FIELD,
payload: {
fieldKey,
value
}
})
}
const clearField = (fieldKey: string) => {
dispatch({
type: CLEAR_FIELD,
payload: {
fieldKey
}
})
}
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
onSearch(fields)
}
const handleClear = () => {
dispatch({
type: RESET
})
onClear && onClear()
}
return (
<SearchFormProvider
value={{
fields,
setFieldValue,
clearField
}}
>
<Container onSubmit={handleSubmit} {...restProps}>
<Fields>{children}</Fields>
<Buttons>
<Button type="submit" size="sm">
Search
</Button>
<Button
type="button"
size="sm"
variant="secondary"
onClick={handleClear}
>
Clear
</Button>
</Buttons>
</Container>
</SearchFormProvider>
)
}
export default SearchForm