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

add task react_movies-list-add-form #2120

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ You have the `App` with the `MoviesList` and `NewMovie` form containing ready
to use `TextField` components. Learn how it works and implement an ability to
add movies from [IMDB](https://www.imdb.com/).

If you want to test your page you can get first image from a [movie page](https://www.imdb.com/title/tt1312171) using `DevTools` -> `Network` -> `Img`
If you want to test your page you can get first image from a [movie page](https://www.imdb.com/title/tt1312171) using `DevTools` -> `Network` -> `Img`

> Here is [the demo page](https://mate-academy.github.io/react_movies-list-add-form/)

Expand All @@ -30,4 +30,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://P-Nazar.github.io/react_movies-list-add-form/) and add it to the PR description.
4 changes: 4 additions & 0 deletions src/App.scss
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
iframe {
display: none;
}

.page {
display: grid;
grid-template: auto / 1fr 400px;
Expand Down
14 changes: 12 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
import './App.scss';
import { useState } from 'react';
import { MoviesList } from './components/MoviesList';
import { NewMovie } from './components/NewMovie';
import moviesFromServer from './api/movies.json';
import { Movie } from './types/Movie';

export const App = () => {
const [movieList, setMovieList] = useState<Movie[]>(moviesFromServer);

const handleAddMovie = (newMovie: Movie) => {
setMovieList((prevMovies) => [...prevMovies, newMovie]);
};

return (
<div className="page">
<div className="page-content">
<MoviesList movies={moviesFromServer} />
<MoviesList movies={movieList} />
</div>
<div className="sidebar">
<NewMovie /* onAdd={(movie) => {}} */ />
<NewMovie
onAdd={handleAddMovie}
/>
</div>
</div>
);
Expand Down
88 changes: 75 additions & 13 deletions src/components/NewMovie/NewMovie.tsx
Original file line number Diff line number Diff line change
@@ -1,45 +1,106 @@
import { useState } from 'react';
import { TextField } from '../TextField';
import { Movie } from '../../types/Movie';

export const NewMovie = () => {
interface Props {
onAdd: (movie: Movie) => void

}

const urlValidator = (urlString: 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]*))?)$/;

if (!urlString.match(pattern)) {
return false;
}

return true;
};

const initialMovieState = {
title: '',
description: '',
imgUrl: '',
imdbUrl: '',
imdbId: '',
};

export const NewMovie: React.FC<Props> = ({ onAdd }) => {
// 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 [newMovie, setNewMovie] = useState<Movie>(initialMovieState);

const isDisabled = !newMovie.title.trim()
|| !urlValidator(newMovie.imgUrl) || !urlValidator(newMovie.imdbUrl)
|| !newMovie.imdbId.trim();

function addMovie(event: React.FormEvent) {
event.preventDefault();

onAdd({
title: newMovie.title.trim(),
description: newMovie.description.trim(),
imgUrl: newMovie.imgUrl.trim(),
imdbUrl: newMovie.imdbUrl.trim(),
imdbId: newMovie.imdbId.trim(),
});

setNewMovie(initialMovieState);

setCount(prev => prev + 1);
}

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;

setNewMovie((prevMovie) => ({ ...prevMovie, [name]: value }));
};

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

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

<TextField
name="description"
label="Description"
value=""
value={newMovie.description}
onChange={handleChange}
/>

<TextField
name="imgUrl"
label="Image URL"
value=""
value={newMovie.imgUrl}
onChange={handleChange}
checkUrl={urlValidator}
required
/>

<TextField
name="imdbUrl"
label="Imdb URL"
value=""
value={newMovie.imdbUrl}
onChange={handleChange}
checkUrl={urlValidator}
required
/>

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

<div className="field is-grouped">
Expand All @@ -48,6 +109,7 @@ export const NewMovie = () => {
type="submit"
data-cy="submit-button"
className="button is-link"
disabled={isDisabled}
>
Add
</button>
Expand Down
11 changes: 8 additions & 3 deletions src/components/TextField/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ type Props = {
label?: string,
placeholder?: string,
required?: boolean,
onChange?: (newValue: string) => void,
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void,
checkUrl?: (urlString: string) => boolean,
};

function getRandomDigits() {
Expand All @@ -23,13 +24,14 @@ export const TextField: React.FC<Props> = ({
placeholder = `Enter ${label}`,
required = false,
onChange = () => {},
checkUrl = undefined,
}) => {
// 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;
const hasError = touched && required && !value.trim();

return (
<div className="field">
Expand All @@ -39,6 +41,7 @@ export const TextField: React.FC<Props> = ({

<div className="control">
<input
name={name}
type="text"
id={id}
data-cy={`movie-${name}`}
Expand All @@ -47,14 +50,16 @@ export const TextField: React.FC<Props> = ({
})}
placeholder={placeholder}
value={value}
onChange={event => onChange(event.target.value)}
onChange={event => onChange(event)}
onBlur={() => setTouched(true)}
/>
</div>

{hasError && (

Choose a reason for hiding this comment

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

trim value in hasError counting for correct show error message when fill input only with empty spaces.
const hasError = touched && required && !value.trim();

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

{((touched && value) && (checkUrl && !checkUrl(value))) && (<p className="help is-danger">{`${label} incorrect URL`}</p>)}
</div>
);
};
Loading