Skip to content

Commit

Permalink
create a custom Hook reusing form logic
Browse files Browse the repository at this point in the history
  • Loading branch information
jessilyneh committed Mar 3, 2022
1 parent 103f5b8 commit 29fe9ca
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 19 deletions.
34 changes: 15 additions & 19 deletions src/index.js
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")
)
);
10 changes: 10 additions & 0 deletions src/useInput.js
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)
];
}

0 comments on commit 29fe9ca

Please sign in to comment.