Created
November 12, 2020 03:54
-
-
Save gmwill934/bb0c386868a40383629e7954ac7adff1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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