Skip to content

Commit 7733495

Browse files
committed
Built-in form validation
1 parent 268734a commit 7733495

File tree

2 files changed

+65
-2
lines changed

2 files changed

+65
-2
lines changed

src/App.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import React, { Fragment } from 'react';
22
import './App.css';
33

4-
import BookList from './components/BookList/BookList';
4+
import BookFormBuildInValidation from './components/BookFormBuildInValidation/BookFormBuildInValidation';
55

66
const App: React.FC = () => {
77
return (
88
<Fragment>
9-
<BookList />
9+
<BookFormBuildInValidation title={'Create a new Book'} />
1010
</Fragment>
1111
);
1212
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import React, { useState } from 'react';
2+
3+
interface BookFormBuildInValidationProps {
4+
book?: {
5+
title: string,
6+
isbn: string
7+
},
8+
title: string,
9+
handleSubmit?: Function;
10+
}
11+
12+
export const BookFormBuildInValidation: React.FC<BookFormBuildInValidationProps> = ({ handleSubmit, title: header, book = { title: '', isbn: '' } }) => {
13+
14+
const [title, setTitle] = useState<string>(book.title);
15+
const [isbn, setIsbn] = useState<string | undefined>(book.isbn);
16+
17+
function handleTitleChange({ target: { value } }: React.ChangeEvent<HTMLInputElement>) {
18+
setTitle(value);
19+
}
20+
21+
function handleIsbnChange({ target: { value } }: React.ChangeEvent<HTMLInputElement>) {
22+
setIsbn(value);
23+
}
24+
25+
function sendForm(event: React.FormEvent<HTMLFormElement>) {
26+
event.preventDefault();
27+
console.log({
28+
title,
29+
isbn
30+
});
31+
if (handleSubmit) {
32+
handleSubmit({
33+
title,
34+
isbn
35+
})
36+
}
37+
}
38+
39+
return (
40+
<form onSubmit={sendForm}>
41+
<h1>{header}</h1>
42+
<label htmlFor="bookTitle">Title: </label>
43+
<input id="bookTitle"
44+
name="bookTitle"
45+
type="text"
46+
required
47+
value={title}
48+
onChange={handleTitleChange} />
49+
<br />
50+
<label htmlFor="bookIsbn">ISBN: </label>
51+
<input id="bookIsbn"
52+
name="bookIsbn"
53+
type="text"
54+
required
55+
value={isbn}
56+
onChange={handleIsbnChange} />
57+
<br />
58+
<button>Send</button>
59+
</form>);
60+
61+
}
62+
63+
export default BookFormBuildInValidation;

0 commit comments

Comments
 (0)