Skip to content

Commit

Permalink
solution
Browse files Browse the repository at this point in the history
  • Loading branch information
InnaSh23 committed Jan 17, 2024
1 parent be2caa8 commit ebbfca4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
14 changes: 10 additions & 4 deletions src/components/NewMovie/NewMovie.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,18 @@ export const NewMovie: React.FC<Props> = ({ onAdd }) => {
setIsFormValid(false);
};

const correctImgUrl = pattern.test(imgUrl);
const correctimdbUrl = pattern.test(imdbUrl);

// const isValid
// = !!title && pattern.test(imgUrl) && pattern.test(imdbUrl) && !!imdbId;

const handleInputChange = (
setter: React.Dispatch<React.SetStateAction<string>>, value: string,
) => {
const isValid = !!title && pattern.test(imgUrl)
&& pattern.test(imdbUrl) && !!imdbId;

setter(value);
setIsFormValid(isValid);

setIsFormValid(isFormValid);
};

const handleSubmit = (event: React.FormEvent) => {
Expand Down Expand Up @@ -88,6 +92,7 @@ export const NewMovie: React.FC<Props> = ({ onAdd }) => {
label="Image URL"
value={imgUrl}
onChange={(value) => handleInputChange(setImgUrl, value)}
isValid={correctImgUrl}
required
/>

Expand All @@ -96,6 +101,7 @@ export const NewMovie: React.FC<Props> = ({ onAdd }) => {
label="Imdb URL"
value={imdbUrl}
onChange={(value) => handleInputChange(setImdbUrl, value)}
isValid={correctimdbUrl}
required
/>

Expand Down
4 changes: 3 additions & 1 deletion 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,
isValid?: boolean,
};

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

const handleTouchedChange = (event: React.ChangeEvent<HTMLInputElement>) => {
onChange(event.target.value);
Expand Down

0 comments on commit ebbfca4

Please sign in to comment.