ghost-keychain/packages/extension-ui/src/components/ValidatedInput.tsx
Ivan Rukhavets 1af44b4264
Add validation to text inputs (#299)
* Add validation to text inputs (#56)

* [CI Skip] 0.24.0-beta.3

skip-checks: true

* Change imports

* Refactor ValidatedInput.tsx to stop cloning elements

* Fix linter

* Fix lint

Co-authored-by: Github Actions <action@github.com>
2020-04-02 11:19:42 +02:00

65 lines
2.0 KiB
TypeScript

// Copyright 2019 @polkadot/extension-ui authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { Result, Validator } from '../validators';
interface BasicProps {
isError?: boolean;
value?: string;
onChange?: (value: string) => void;
}
type Props<T extends BasicProps> = T & {
className?: string;
validator: Validator<string>;
component: React.ComponentType<T>;
onValidatedChange: (value: string | null) => void;
}
function ValidatedInput<T extends object> ({ className, component: Input, onValidatedChange, validator, ...props }: Props<T>): React.ReactElement<Props<T>> {
const [value, setValue] = useState('');
const [wasMounted, setWasMounted] = useState(false);
const [validationResult, setValidationResult] = useState<Result<string>>(Result.ok(''));
useEffect(() => {
if (!wasMounted) {
setWasMounted(true);
return;
}
(async (): Promise<void> => {
const result = await validator(value);
setValidationResult(result);
onValidatedChange(Result.isOk(result) ? value : null);
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value, validator, onValidatedChange]);
return (
<div className={className}>
<Input {...props as T}
isError={Result.isError(validationResult)}
onChange={setValue}
value={value} />
{Result.isError(validationResult) && <ErrorMessage>{validationResult.error.errorDescription}</ErrorMessage>}
</div>
);
}
const ErrorMessage = styled.span`
display: block;
margin-top: -10px;
font-size: ${({ theme }): string => theme.labelFontSize};
line-height: ${({ theme }): string => theme.labelLineHeight};
color: ${({ theme }): string => theme.errorColor};
`;
ErrorMessage.displayName = 'ErrorMessage';
export default ValidatedInput;