Creating a Form component

Let's perform the following steps to create a generic Form component:

  1. Create a new file called Form.tsx with the following import statements:
import { FC, useState } from 'react';
import { PrimaryButton, gray5, gray6 } from './Styles';
/** @jsx jsx */
import { css, jsx } from '@emotion/core';
  1. Let's define interface for the form field values:
export interface Values {
[key: string]: any;
}

We haven't used an interface defined in this way before. This is called an indexable type.

An indexable type is where the index signature is defined rather than specific properties. The type in the square brackets defines the type for the keys in the object and the type after the colon defines the return type when indexed.

In our case, the key will be the field name, and the value will be the field value. So, Values could be as follows:

{
title: "Why should I learn TypeScript?",
content: "TypeScript seems to be getting popular so I wondered
whether it is worth my time learning it? What benefits does it
give over JavaScript?"
}
  1. Let's move on to define the props interface, which is going to have a single prop for the Submit button caption: 
interface Props {
submitCaption?: string;
}
  1. Let's begin to implement the Form function component starting with destructuring the props:
export const Form: FC<Props> = ({ submitCaption, children }) =>
null;

Notice that we have included the children prop, which we are going to use later to render content nested within the form.

  1. Let's create some state for the field value, using the interface we created earlier:
export const Form: FC<Props> = ({ submitCaption, children }) => {
const [values, setValues] = useState<Values>({});
return null;
};

Notice that we set the initial state to an empty object literal.

  1. Let's now define the JSX for the form:
return (
<form noValidate={true}>
<fieldset
css={css`
margin: 10px auto 0 auto;
padding: 30px;
width: 350px;
background-color: ${gray6};
border-radius: 4px;
border: 1px solid ${gray5};
box-shadow: 0 3px 5px 0 rgba(0, 0, 0, 0.16);
`}
>
{children}
<div
css={css`
margin: 30px 0px 0px 0px;
padding: 20px 0px 0px 0px;
border-top: 1px solid ${gray5};
`}
>
<PrimaryButton type="submit">
{submitCaption}
</PrimaryButton>
</div>
</fieldset>
</form>
);

So, we have created a form tag that has a standard HTML form validation suppressed because we are going to handle that ourselves later in this chapter.

The form contains a fieldset tag that will hold the form content along with a container for our Submit button, which will have a faint horizontal line at the top.

We then render any nested child components before the Submit button using the children prop.

That completes the Form component for the time being.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.81.210