Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

movies-list-add-form #2085

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const App = () => {
<MoviesList movies={moviesFromServer} />
</div>
<div className="sidebar">
<NewMovie /* onAdd={(movie) => {}} */ />
<NewMovie />
</div>
</div>
);
Expand Down
17 changes: 16 additions & 1 deletion src/components/NewMovie/NewMovie.scss
Original file line number Diff line number Diff line change
@@ -1 +1,16 @@
// not empty
.new-movie-form {
display: flex;
flex-direction: column;
align-items: flex-end; /* Align items to the right */
}

.form-field {
margin-bottom: 10px; /* Add some spacing between fields */
display: flex;
flex-direction: column;
align-items: flex-end; /* Align items to the right */
}

label {
margin-bottom: 5px;
}
123 changes: 109 additions & 14 deletions src/components/NewMovie/NewMovie.tsx
Original file line number Diff line number Diff line change
@@ -1,45 +1,134 @@
import { useState } from 'react';
import React, { useState } from 'react';
import { TextField } from '../TextField';

export const NewMovie = () => {
// Increase the count after successful form submission
// to reset touched status of all the `Field`s
const [count] = useState(0);
export const NewMovie: React.FC = () => {
const [count, setCount] = useState(0);

const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [imgUrl, setImgUrl] = useState('');
const [imdbUrl, setImdbUrl] = useState('');
const [imdbId, setImdbId] = useState('');

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can combine it in one useState

const [newMovie, setNewMovie] = useState({
  title: '',
  ...
})

now we can also create only one handle function for all fields

const handleChange = (e: ...) => {
  const {name, value} = e.target;
  setMovie((prevMovie) => ({...prevMovie, [name]: value}))
}

don't forget to specify name attr to input in TextField


const [titleError, setTitleError] = useState(false);
const [imgUrlError, setImgUrlError] = useState(false);
const [imdbUrlError, setImdbUrlError] = useState(false);
const [imdbIdError, setImdbIdError] = useState(false);

const [isFormSubmitted, setIsFormSubmitted] = useState(false);

const resetForm = () => {
setTitle('');
setDescription('');
setImgUrl('');
setImdbUrl('');
setImdbId('');

setTitleError(false);
setImgUrlError(false);
setImdbUrlError(false);
setImdbIdError(false);

setIsFormSubmitted(false);
setCount(prevCount => prevCount + 1);
};

const validateUrl = (url: string): boolean => {
// eslint-disable-next-line max-len
const pattern = /^((([A-Za-z]{3,9}:(?:\/\/)?)?(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www\.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@,.\w_]*)#?(?:[,.!/\\\w]*))?)$/;

return pattern.test(url);
};

const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();

setTitleError(!title.trim());
setImgUrlError(!imgUrl.trim());
setImdbUrlError(!imdbUrl.trim());
setImdbIdError(!imdbId.trim());

if (title.trim() && imgUrl.trim() && imdbUrl.trim() && imdbId.trim()) {
if (!validateUrl(imgUrl)) {
setImgUrlError(true);
setIsFormSubmitted(true);

return;
}

if (!validateUrl(imdbUrl)) {
setImdbUrlError(true);
setIsFormSubmitted(true);

return;
}

resetForm();
}

setIsFormSubmitted(true);
};

return (
<form className="NewMovie" key={count}>
<form className="NewMovie" key={count} onSubmit={handleSubmit}>
<h2 className="title">Add a movie</h2>

<TextField
name="title"
label="Title"
value=""
onChange={() => {}}
value={title}
onChange={(newValue) => setTitle(newValue)}
required
error={titleError ? 'Title is required' : undefined}
onBlur={() => setIsFormSubmitted(true)}
/>

<TextField
name="description"
label="Description"
value=""
value={description}
onChange={(newValue) => setDescription(newValue)}
/>

<TextField
name="imgUrl"
label="Image URL"
value=""
value={imgUrl}
onChange={(newValue) => setImgUrl(newValue)}
onBlur={() => setImgUrlError(!imgUrl.trim())}
required
showError={isFormSubmitted}
error={
(imgUrlError && 'Image URL is required')
|| (isFormSubmitted && !validateUrl(imgUrl) && 'Invalid Image URL')
|| undefined
}
/>

<TextField
name="imdbUrl"
label="Imdb URL"
value=""
label="IMDb URL"
value={imdbUrl}
onChange={(newValue) => setImdbUrl(newValue)}
onBlur={() => setImdbUrlError(!imdbUrl.trim())}
required
showError={isFormSubmitted}
error={
(imdbUrlError && 'IMDb URL is required')
|| (isFormSubmitted && !validateUrl(imdbUrl) && 'Invalid IMDb URL')
|| undefined
}
/>

<TextField
name="imdbId"
label="Imdb ID"
value=""
label="IMDb ID"
value={imdbId}
onChange={(newValue) => setImdbId(newValue)}
onBlur={() => setImdbIdError(!imdbId.trim())}
required
showError={isFormSubmitted}
error={imdbIdError ? 'IMDb ID is required' : undefined}
/>

<div className="field is-grouped">
Expand All @@ -48,6 +137,12 @@ export const NewMovie = () => {
type="submit"
data-cy="submit-button"
className="button is-link"
disabled={
!title.trim()
|| !imgUrl.trim()
|| !imdbUrl.trim()
|| !imdbId.trim()
}
>
Add
</button>
Expand Down
39 changes: 26 additions & 13 deletions src/components/TextField/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ import classNames from 'classnames';
import React, { useState } from 'react';

type Props = {
name: string,
value: string,
label?: string,
placeholder?: string,
required?: boolean,
onChange?: (newValue: string) => void,
name: string;
value: string;
label?: string;
placeholder?: string;
required?: boolean;
onChange?: (newValue: string) => void;
onBlur?: () => void;
showError?: boolean;
error?: string | undefined;
};

function getRandomDigits() {
Expand All @@ -23,11 +26,11 @@ export const TextField: React.FC<Props> = ({
placeholder = `Enter ${label}`,
required = false,
onChange = () => {},
onBlur = () => {},
showError = false,
error,
}) => {
// generage a unique id once on component load
const [id] = useState(() => `${name}-${getRandomDigits()}`);

// To show errors only if the field was touched (onBlur)
const [touched, setTouched] = useState(false);
const hasError = touched && required && !value;

Expand All @@ -43,18 +46,28 @@ export const TextField: React.FC<Props> = ({
id={id}
data-cy={`movie-${name}`}
className={classNames('input', {
'is-danger': hasError,
'is-danger': showError && hasError,
})}
placeholder={placeholder}
value={value}
onChange={event => onChange(event.target.value)}
onBlur={() => setTouched(true)}
onChange={(event) => {
setTouched(false);
onChange(event.target.value);
}}
onBlur={() => {
setTouched(true);
onBlur();
}}
/>
</div>

{hasError && (
{showError && hasError && (
<p className="help is-danger">{`${label} is required`}</p>
)}

{showError && error && (
<p className="help is-danger">{error}</p>
)}
</div>
);
};