Skip to content

Instantly share code, notes, and snippets.

@gmwill934
Created November 12, 2020 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmwill934/bb0c386868a40383629e7954ac7adff1 to your computer and use it in GitHub Desktop.
Save gmwill934/bb0c386868a40383629e7954ac7adff1 to your computer and use it in GitHub Desktop.
import React, {FC, useState} from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const someErrorsComingFromAnExpressAPI = {
username: [
'Username required',
'Username must be 3 characters or more',
'Another error for the username',
],
firstName: ['First name required'],
password: [
'Password is required',
'Password is not secure',
'Password cannot be 1234',
],
};
interface IInputField {
errors?: string[] | null;
nameId: string;
value: string | number;
label: string;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}
interface IError {
error: string;
}
const Error: FC<IError> = ({error}) => {
return <small style={{color: 'red', margin: '10px'}}>{error}</small>;
};
export const InputField: FC<IInputField> = ({
errors,
label,
nameId,
value,
onChange,
}) => {
return (
<>
<label htmlFor={nameId}>{label}</label>
<input
type='text'
id={nameId}
name={nameId}
value={value}
onChange={onChange}
/>
{errors &&
errors.map((e, i: number) => {
return <Error key={i} error={e} />;
})}
</>
);
};
const ErrorProposal: FC = () => {
const [username, setUsername] = useState<string>('');
const [firstName, setFirstName] = useState<string>('');
const [password, setPassword] = useState<string>('');
const [isError, setIsError] = useState<boolean>(false);
return (
<>
<InputField
errors={isError ? someErrorsComingFromAnExpressAPI.username : null}
label='Username'
nameId='username'
value={username}
onChange={e => setUsername(e.currentTarget.value)}
/>
<br />
<InputField
errors={isError ? someErrorsComingFromAnExpressAPI.firstName : null}
label='First Name'
nameId='firstName'
value={firstName}
onChange={e => setFirstName(e.currentTarget.value)}
/>
<br />
<InputField
errors={isError ? someErrorsComingFromAnExpressAPI.password : null}
label='Password'
nameId='password'
value={password}
onChange={e => setPassword(e.currentTarget.value)}
/>
<br />
<button onClick={() => setIsError(prevState => !prevState)}>
Trigger Errors
</button>
</>
);
};
ReactDOM.render(<ErrorProposal />, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment