-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
create a custom Hook reusing form logic
- Loading branch information
1 parent
103f5b8
commit 29fe9ca
Showing
2 changed files
with
25 additions
and
19 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,42 +1,38 @@ | ||
import React, {useState} from "react"; | ||
import React from "react"; | ||
import ReactDOM from "react-dom"; | ||
import "./index.css"; | ||
import { useInput } from "./useInput"; | ||
|
||
// useInput will received a value (nameProps) | ||
// and atribute the initial value (resetName) | ||
export default function App() { | ||
const [name, setName] = useState("") | ||
const [birth, setBirth]= useState("") | ||
const [nameProps, resetName] = useInput(""); | ||
const [birthProps, resetBirth] = useInput(""); | ||
|
||
//controlled components are those in which | ||
// form data is handled by the component's state | ||
const submit = (e) => { | ||
e.preventDefault(); | ||
alert(`${name} was born in ${birth}`); | ||
setName("") | ||
setBirth("") | ||
alert(`${nameProps.value} was born in ${birthProps.value}`); | ||
resetBirth(); | ||
resetName(); | ||
}; | ||
|
||
// just need pass nameProps to value ({value, | ||
// onChange}, resetValue) inside {...nameProps} | ||
|
||
return ( | ||
<form onSubmit={submit}> | ||
<input value={name} | ||
type="text" | ||
placeholder="name..." | ||
onChange={(e)=> setName(e.target.value)} | ||
/> | ||
<input {...nameProps} type="text" placeholder="name..." /> | ||
|
||
<input value={birth} | ||
type="date" | ||
onChange={(e)=> setBirth(e.target.value)} | ||
/> | ||
<input {...birthProps} type="date" /> | ||
|
||
<button>Submit</button> | ||
</form> | ||
); | ||
} | ||
|
||
|
||
ReactDOM.render( | ||
<React.StrictMode> | ||
<App /> | ||
</React.StrictMode>, | ||
document.getElementById("root") | ||
) | ||
); |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import { useState } from "react"; | ||
// import useState to use hooks inside hooks | ||
|
||
export function useInput(initialValue) { | ||
const [value, setValue] = useState(initialValue); | ||
return [ | ||
{ value, onChange: (e) => setValue(e.target.value) }, | ||
() => setValue(initialValue) | ||
]; | ||
} |