Skip to content

Commit 42a9baf

Browse files
committed
feat: 🎸 custom hook for using input
1 parent ec39bd3 commit 42a9baf

File tree

5 files changed

+48
-2
lines changed

5 files changed

+48
-2
lines changed

2024 Prep/machine_coding/react/src/App.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import './App.css'
2-
import { LiftingUpState } from './components'
2+
import { InputHookComp } from './components'
33

44
function App() {
55
return (
66
<div className="container">
77
<h1>Vite + React</h1>
8-
<LiftingUpState />
8+
<InputHookComp />
99
</div>
1010
)
1111
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { useInput } from '../hooks'
2+
3+
function InputHookComp() {
4+
const input = useInput({
5+
initialValue: '',
6+
})
7+
8+
return (
9+
<>
10+
<input
11+
type="text"
12+
value={input.value}
13+
onChange={input.handleChange}
14+
placeholder="Enter your name here"
15+
/>
16+
<h4>value: {input.value}</h4>
17+
<button onClick={input.reset}>Reset</button>
18+
</>
19+
)
20+
}
21+
22+
export default InputHookComp

2024 Prep/machine_coding/react/src/components/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import FileExplorer from './FileExplorer'
44
import BatchingStates from './BatchingStates'
55
import CountDownTimer from './Timer'
66
import LiftingUpState from './LiftingStateUp'
7+
import InputHookComp from './InputCustomHookComp'
78

89
export {
910
Loader,
@@ -12,4 +13,5 @@ export {
1213
BatchingStates,
1314
CountDownTimer,
1415
LiftingUpState,
16+
InputHookComp,
1517
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export { useFetch } from './useFetchAsync'
22
export { useDebounce } from './useDebounce'
3+
export { useInput } from './useInput'
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { useState } from 'react'
2+
3+
export interface IUseInputProps {
4+
initialValue: string | undefined
5+
}
6+
const useInput = (props: IUseInputProps) => {
7+
const { initialValue = '' } = props
8+
9+
const [value, setValue] = useState<string>(initialValue)
10+
11+
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
12+
setValue(event.target.value)
13+
}
14+
15+
const reset = () => {
16+
setValue(initialValue)
17+
}
18+
return { value, handleChange, reset }
19+
}
20+
21+
export { useInput }

0 commit comments

Comments
 (0)