Last active
February 9, 2022 13:22
-
-
Save m7kvqbe1/a89bf90c35bd96a0e89400863248ead6 to your computer and use it in GitHub Desktop.
react-component-library Field
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 styled from "styled-components"; | |
| const StyledField = styled.div``; | |
| const StyledErrorMessage = styled.span``; | |
| const StyledHintText = styled.span`` | |
| function Field({ hintText, errors, children, ...rest }) { | |
| // Function as Child Component (FaCC - pretty render prop) | |
| // Apply opinionated form field styling (spacing) | |
| // Apply a11y | |
| return ( | |
| <StyledField> | |
| {hintText && <StyledHintText>{hintText}</StyledHintText>} | |
| {children(...rest)} | |
| {errors.map((error) => { | |
| <StyledErrorMessage>{error}</StyledErrorMessage>; | |
| })} | |
| </StyledField> | |
| ); | |
| } | |
| // Like `Field` but for a collection | |
| function Fieldset(...) { | |
| // Single hint text above, errors displayed at bottom | |
| // ... | |
| } | |
| function app() { | |
| // Application code to form compatible object | |
| const errors = { | |
| required: "Message text associated with the error", | |
| }; | |
| return ( | |
| <Field hintText="Hello, World!" errors={errors}> | |
| {({ errors, ...rest }) => ( | |
| <TextInputE isInvalid={!isEmpty(errors)} {...rest} /> | |
| )} | |
| </Field> | |
| ); | |
| } | |
| // - The `isInvalid` prop could be applied within the `Field` component instead of in app code via `cloneElement` | |
| // - The FaCC probably isn't needed by our components because they all implement the `InputValidationProps` interface | |
| // - FaCC does however allow downstream teams to use third party (or indeed thier own) implementations that do not conform | |
| // - Formik already has a `Field` component it uses for automagically injecting state (namespace clash) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Formik Potential Usage Example