npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@simpozio/contact-form

v1.0.1

Published

Package for Contact Form component

Downloads

8

Readme

Contact Form

Package for Contact Form component. Contains generic Form component and presets: Short

Installation

npm i @simpozio/contact-form

Usage

You can use generic component Form and construct your own view for it:

import {Form, Field} from '@simpozio/contact-form';

const Component = () => {
    const initialValues = {
        name: ''
    }

    const onChange = () => Promise.resolve(console.log('Form Updated'));

    const onValidate = ({fields}) => {
        return Promise.resolve(_.mapValues(fields, value => (value => !!value));
    }

    const onValid = ({fields}) => console.log('Form is valid!', fields);

    const onSubmit = ({values, resetForm}) => {
            return new Promise((resolve, reject) => {
                try {
                   api.post(values)
                    .then(resolve)
                    .then(() => {
                        resetForm()
                    })
                } catch(e) {
                   reject(e);
                };
            }
        }

    const onError = ({error, resetForm}) => {
        console.log(error);
        resetForm();
    };

    return (
        <Form
            initialValues={initialValues}
            onChange={onChange}
            onValid={onValid}
            onValidate={onValidate}
            onSubmit={onSubmit}
            onError={onError}
        >
            {({
                fields,
                formError,
                onChange,
                isValid,
                isSubmitting,
                updateForm,
                submitForm,
                resetForm
            }) => (
                <Field
                    label="name"
                    name="name"
                    field={fields["name"]}
                    onChange={onChange}
                    onBlur={updateForm}
                />

                {formError && <p>{formError}</p>}

                <button onClick={submitForm} disabled={!isValid || isSubmitting}>Submit</button>
                <button onClick={resetForm}>Reset</button>
            )}
        </Form>
    )
}

Or you can you preset with predefined structure, e.g. Short:

import {ShortForm} from '.@simpozio/contact-form/dist/presets';

const StyledShortForm = styled(ShortForm)`
  min-height: 750px;

  @media (max-width: 767px) {
    min-height: 580px;
  }
`;

const Component = () => {
    const fields = {
        name: {
          label: 'Your name',
          initialValue: ''
        },
        phone: {
          label: 'Your phone',
          initialValue: ''
        },
        email: {
          label: 'Your email',
          initialValue: ''
        }
      };

    const onChange = () => Promise.resolve(console.log('Form Updated'));

    const onValidate = ({fields}) => {
        return Promise.resolve(_.mapValues(fields, value => (value => !!value));
    }

    const onValid = ({fields}) => console.log('Form is valid!', fields);

    const onSubmit = ({values, resetForm}) => {
            return new Promise((resolve, reject) => {
                try {
                   api.post(values)
                    .then(resolve)
                    .then(() => {
                        resetForm()
                    })
                } catch(e) {
                   reject(e);
                };
            }
        }

    const onError = ({error, resetForm}) => {
        console.log(error);
        resetForm();
    };

    return (
        <StyledShortForm
          formText={'The price for this model starts at £300,000'}
          bottomText={
            'We collect your data to keep you updated about our reservation program. By submitting this form you agree to the Privacy Policy.'
          }
          fields={fields}
          onValidate={onValidate}
          onChange={onChange}
          onSubmit={onSubmit}
          onError={onError}
        />
    );
};

Styling

Form component is generic, so it don't have any styles. So you need to add styles by yourself with css or with styled component. Preset have default styles, and you can style them in 3 ways:

Theming

Preset accepts theme props, so you can pass theme from your styled-components theme context to preset component:

import {useContext} from 'react';
import styled, {ThemeContext} from 'styled-components';
import {ShortForm} from '@simpozio/contact-form/dist/presets';

const Component = (props) => {
    const theme = useContext(ThemeContext);

    return (
        <ShortForm {...props} theme={theme} />
    )
}

Styled Components

Default styling with styled components

import styled from 'styled-components';
import {ShortForm} from '@simpozio/contact-form/dist/presets';

const StyledForm = styled(ShortForm)`
    color: #fff;
    backgroung-color: #000;
`

const Component = (props) => {
    return (
        <StyledForm {...props} />
    )
}

Custom Styles

Preset supports styles with interpolated string from styled-components:

import styled, {css} from 'styled-components';
import {ShortForm} from '@simpozio/contact-form/dist/presets';

const customStyles = css(({Field, BottomText}) => css`
    ${Field} {
        color: #fff;
        backgroung-color: #000;
    }

    ${BottomText} {
        font-size: 0.8rem;
    }
`

const Component = (props) => {
    return (
        <StyledForm {...props} styles={customStyles} />
    )
}

Properties

Form

Form accepts standard HTML attributes as props: action, method, className. And form have it's own additional properties: fields, isSubmitted, isValid: boolean, error, resetForm

  • initialValues: {[key: string]: string} - object with default values for fields
  • onChange: ({fields, isSubmitted, isValid}) => Promise<newFields> - callback called when form was updated via updateForm() method. It accepts object with fields and it's values, and optionally can return fields with new values. It can be used to modify fields values in dependency of other values of form changes.
  • onValidate: ({fields, isSubmitted, isValid}) => Promise<object> - callback called when form was validated. It accepts object with fields and it's values, and should return fields with boolean values (valid/not valid).
  • onValid: ({fields, isSubmitted, isValid}) => void - callback called when form become valid, after onValidate() check
  • onSubmit: ({fields, isSubmitted, isValid, resetForm}) => Promise<void> - callback called when form is submitting via submitForm() method. It accepts object with fields and it's values, and optionally can return error that will be passed to onError callback. Also accepts resetForm() method as second argument.
  • onError: ({fields, isSubmitted, isValid, error, resetForm}) => void - callback called when form is errored (after onSubmit callback). It accepts error string passed form onSubmit callback as first argument, and resetForm() method as second argument.

Form accepts children as function, and will pass methods and state to this function:

  • fields - object with field name as keys, and object with value, field error and touched properties as value.
    • value: string - field value
    • error: boolean - validation state of field
    • touched: boolean - becomes true when value of field is different from the initial
  • formError: string - string with for error passed from onSubmit callback
  • onChange: (name, value) => void - onchange handler for fields, should be passed to onChange callback of fields
  • isValid: boolean - becomes true when all fields are valid after onValidate callback,
  • isSubmitted: boolean - prop that shows submitted state of form
  • isSubmitting: boolean - props that show is submitting in process
  • updateForm: () => void - method for call form onChange callback (e.g. for saving values to redux)
  • submitForm: () => void - method for submitting form, will call onSubmit callback
  • resetForm: () => void - method for resetting form to initialValues

Field

Fields accepts props passed to MUI Text Field: className, name, type, label, placeholder, required, disabled.

  • field: {value: string, error: boolean, touched: boolean} - field object, contains value, validation state in error prop, and touched state if vields value is different from initial value
  • onChange: (name, value) => void - accepts onChange handler passed from form
  • onBlur: (event) => void - accepts onBlur handler, it can be used to update form via updateForm() method

Caption

Component for form text, that accepts HTML string and render it as children.

  • className: string - standard prop for styling
  • html: string - you can pass HTML string that will be inserted as children via dangerouslySetInnerHTML prop. If passed - children props will be ignored.
  • children - standard children prop to render child components. It will be ignored if html prop is passed.
<Caption html="<span>This text will be rendered as <b>html</b></span>">
    This text will be ignored!
</Caption>

<Caption>
    <span>This text will be rendered as regular <b>children</b></span>
</Caption>

Presets

Short

Form component with predefined structure.

Properties

It accepts all properties from Form component, except initialValues, and has its own properties:

  • fields: object - fields preset object
    • label: string - field label
    • placeholder: string - field placeholder
    • initialValue: string - field initial value
    • disabled: string - disabled state of field
  • formText: string - HTML string passed to Caption component above the button
  • bottomText: string - HTML string passed to Caption component at the bottom of the form
  • validSchema: yup-schema - validation schema created via yup module
  • styles: string - interpolated styled components string with styles
  • theme: object - theme object

Development

Look simpozio-frontend-common library