Skip to content

Commit

Permalink
solution
Browse files Browse the repository at this point in the history
  • Loading branch information
artur.manuilenko committed Feb 5, 2025
1 parent 9663976 commit 174e0a8
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 15 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ const pattern = /^((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(
- Implement a solution following the [React task guideline](https://github.com/mate-academy/react_task-guideline#react-tasks-guideline).
- Use the [React TypeScript cheat sheet](https://mate-academy.github.io/fe-program/js/extra/react-typescript).
- Open one more terminal and run tests with `npm test` to ensure your solution is correct.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_movies-list-add-form/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://manuilenkoart.github.io/react_movies-list-add-form/) and add it to the PR description.
11 changes: 9 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,22 @@ import './App.scss';
import { MoviesList } from './components/MoviesList';
import { NewMovie } from './components/NewMovie';
import moviesFromServer from './api/movies.json';
import { useState } from 'react';
import { Movie } from './types/Movie';

export const App = () => {
const [movies, setMovies] = useState<Movie[]>(moviesFromServer);
const handleNewMovie = (newMovie: Movie) => {
setMovies(prev => [...prev, newMovie]);
};

return (
<div className="page">
<div className="page-content">
<MoviesList movies={moviesFromServer} />
<MoviesList movies={movies} />
</div>
<div className="sidebar">
<NewMovie /* onAdd={(movie) => {}} */ />
<NewMovie onAdd={handleNewMovie} />
</div>
</div>
);
Expand Down
94 changes: 84 additions & 10 deletions src/components/NewMovie/NewMovie.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,111 @@
import { useState } from 'react';
import React, { useState } from 'react';
import { TextField } from '../TextField';
import { Movie } from '../../types/Movie';

export const NewMovie = () => {
type Props = {
onAdd: (newMovie: Movie) => void;
};

export const NewMovie = ({ onAdd }: Props) => {
// Increase the count after successful form submission
// to reset touched status of all the `Field`s
const [count] = useState(0);
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('');

const hasRequiredData = [imdbId, title, imdbUrl, imgUrl].every(
i => !!i.trim(),
);

const handleSubmitForm = (e: React.FormEvent) => {
e.preventDefault();
const newMovie: Movie = {
imdbId,
title,
description,
imdbUrl,
imgUrl,
};

if (!hasRequiredData) {
return;
}

onAdd(newMovie);
setCount(prev => prev + 1);

//reset
setTitle('');
setDescription('');
setImgUrl('');
setImdbUrl('');
setImdbId('');
};

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

return pattern.test(data) ? null : 'has invalid data field';
};

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

<TextField
name="title"
label="Title"
value=""
onChange={() => {}}
value={title}
onChange={setTitle}
required
/>

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

<TextField name="imgUrl" label="Image URL" value="" />
<TextField
name="imgUrl"
label="Image URL"
value={imgUrl}
onChange={setImgUrl}
validate={handleValidate}
required
/>

<TextField name="imdbUrl" label="Imdb URL" value="" />
<TextField
name="imdbUrl"
label="Imdb URL"
value={imdbUrl}
onChange={setImdbUrl}
validate={handleValidate}
required
/>

<TextField name="imdbId" label="Imdb ID" value="" />
<TextField
name="imdbId"
label="Imdb ID"
value={imdbId}
onChange={setImdbId}
required
/>

<div className="field is-grouped">
<div className="control">
<button
type="submit"
data-cy="submit-button"
className="button is-link"
disabled={!hasRequiredData}
>
Add
</button>
Expand Down
22 changes: 20 additions & 2 deletions src/components/TextField/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type Props = {
placeholder?: string;
required?: boolean;
onChange?: (newValue: string) => void;
validate?: (data: string) => string | null;
};

function getRandomDigits() {
Expand All @@ -21,14 +22,28 @@ export const TextField: React.FC<Props> = ({
placeholder = `Enter ${label}`,
required = false,
onChange = () => {},
validate = () => undefined,
}) => {
// generate 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 [validateError, setValidateError] =
useState<ReturnType<typeof validate>>();

const hasError = touched && required && !value;

const handleBlur = () => {
setTouched(true);

if (validate) {
const err = validate(value);

setValidateError(err);
}
};

return (
<div className="field">
<label className="label" htmlFor={id}>
Expand All @@ -41,16 +56,19 @@ export const TextField: React.FC<Props> = ({
id={id}
data-cy={`movie-${name}`}
className={classNames('input', {
'is-danger': hasError,
'is-danger': hasError || validateError,
})}
placeholder={placeholder}
value={value}
onChange={event => onChange(event.target.value)}
onBlur={() => setTouched(true)}
onBlur={handleBlur}
/>
</div>

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

0 comments on commit 174e0a8

Please sign in to comment.