Building a React Form Component with TypeScript : Introduction
There’s lots of boiler plate code you need to write when building a form in react … managing the field values, validating them, submitting the values to a web api and informing the user of success or any problems.
This is going to be the first of a series of blog posts where we’ll build our own super simple form component. We’ll hopefully encapsulate some of that boiler plate in our form component so we don’t need to code it in our form instances.
We’re going to use some cool stuff in our implementation … We’ll use the new context api as well as the popular render props pattern. We’ll also write our components in TypeScript.
We’ll use our super simple form component to build the following Contact Us form.
In this intro post we’ll simply create our project. So, without further ado, let’s get started …
Getting started
Let’s use TypeScript React Starter to create our project:
create-react-app my-app --scripts-version=react-scripts-ts
We’re going to make use of Bootstrap. So, let’s reference this in public\index.html
:
<head>
...
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
...
</head>
We’re going to get rid of the sample code in App.tsx
and replace it with the following:
import * as React from "react";
class App extends React.Component {
public render() {
return (
<div className="mt-3">
{/* TODO - reference "contact us" form*/}
</div>
);
}
}
export default App;
Let’s also opt out of a few tslint rules in tslint.json
:
{
"extends": ["tslint:recommended", "tslint-react", "tslint-config-prettier"],
"linterOptions": {
"exclude": ["config/**/*.js", "node_modules/**/*.ts"]
},
"rules": { "object-literal-sort-keys": false, "member-ordering": false, "jsx-no-lambda": false, "no-console": false, "ordered-imports": false }}
What’s up next
In the next post we are going to implement very basic Form
and Field
components. We’ll use the render props pattern so that any content can be injected into the form. We’ll also create the 1st version of our “contact us” form.
If you to learn more about using TypeScript with React, you may find my course useful: