Chap06 -> Reducing boilerplat code with React Hook Form -> Refactoring the Header component to use React Hook Form
parent
970dd905dc
commit
c6c6dfd02e
|
@ -2,22 +2,22 @@
|
||||||
import { css } from '@emotion/react';
|
import { css } from '@emotion/react';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Link, useSearchParams } from 'react-router-dom';
|
import { Link, useSearchParams } from 'react-router-dom';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
|
||||||
import { UserIcon } from './Icons';
|
import { UserIcon } from './Icons';
|
||||||
import { fontFamily, fontSize, gray1, gray2, gray5 } from './Styles';
|
import { fontFamily, fontSize, gray1, gray2, gray5 } from './Styles';
|
||||||
|
|
||||||
|
type FormData = {
|
||||||
|
search: string;
|
||||||
|
};
|
||||||
|
|
||||||
export const Header = () => {
|
export const Header = () => {
|
||||||
|
const { register } = useForm<FormData>();
|
||||||
const [searchParams] = useSearchParams();
|
const [searchParams] = useSearchParams();
|
||||||
const criteria = searchParams.get('criteria') || '';
|
const criteria = searchParams.get('criteria') || '';
|
||||||
const [search, setSearch] = React.useState(criteria);
|
|
||||||
|
|
||||||
const handleSearchInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
setSearch(e.currentTarget.value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = (e: React.FormEvent) => {
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
console.log(search);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -49,10 +49,11 @@ export const Header = () => {
|
||||||
</Link>
|
</Link>
|
||||||
<form onSubmit={handleSubmit}>
|
<form onSubmit={handleSubmit}>
|
||||||
<input
|
<input
|
||||||
|
{...register('search')}
|
||||||
|
name="search"
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Search ..."
|
placeholder="Search ..."
|
||||||
value={search}
|
defaultValue={criteria}
|
||||||
onChange={handleSearchInputChange}
|
|
||||||
css={css`
|
css={css`
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
font-family: ${fontFamily};
|
font-family: ${fontFamily};
|
||||||
|
|
Loading…
Reference in New Issue