Skip to content

Instantly share code, notes, and snippets.

@m7kvqbe1
Last active February 9, 2022 13:22
Show Gist options
  • Select an option

  • Save m7kvqbe1/a89bf90c35bd96a0e89400863248ead6 to your computer and use it in GitHub Desktop.

Select an option

Save m7kvqbe1/a89bf90c35bd96a0e89400863248ead6 to your computer and use it in GitHub Desktop.
react-component-library Field
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)
@m7kvqbe1
Copy link
Author

m7kvqbe1 commented Feb 9, 2022

Formik Potential Usage Example

import { Field as FormikField } from "formik";

<FormikField name="firstName">
  {({
    field, // { name, value, onChange, onBlur }
    form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
    meta,
  }) => {
    const errors = {
      required:
        meta.touched && meta.error && "Message text associated with the error",
    };

    return (
      <Field hintText="Hello, World!" errors={errors} {...field}>
        {({ errors, ...rest }) => (
          <TextInputE isInvalid={!isEmpty(errors)} {...rest} />
        )}
      </Field>
    );
  }}
</FormikField>;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment