Material Form UI + ReactJS + TypeScript (Part 1)

Tram Ho

As the title of the article, the content of this article will create a basic form using Material UI , ReactJS and Typescript . So the first thing why do we need typescript? How does Typescript work?

  • The simple reason to use typescripts is that if you want to code more tightly between data type , there is a synchronization between the members in the project, then use typescript.
  • In essence you are not learning a new programming language, but the typescript will be transformed via javascript through Babel and our code is still javascript like before.


Request:

  • Create form for 2 types of text input and checkbox + submit button
  • The form submission data has the form (only need console.log in the executable function): {categories: [1, 2, 3, 4], meta: ["a", "b", "c"]}
  • The meta cannot contain empty data
  • Allow add or remove input text
  • multi checkbox

2. Demo

Before the demo, we also need the basic knowledge:

And install the dependencies as follows:

  • typescript
  • types / react
  • types / react-dom
  • material-ui / core
  • material-ui / lab

Let’s start !!!


For the simple index.js file we just need to inport the Form component we will customize now:

Okay, now let’s do the multi checkboxes first, instead of fixing the hard data checkbox, we will assume that we have a piece of data returned by the server as follows:

Above, I have pass categories through another component, the purpose is that we will handle everything in the form.tsx component and pass the implementation function back to the FormComponent , so in my FormComponent code will be much cleaner. .

Do you find yourself adding a props handleChange to the FormComponent? and it is used to get the clicked checkbox id. The purpose for us to get the selected checkbox values. Ok next we go through the form.tsx and handle function handleChange :

Add Submit button to check the results, huh

Let’s run to see which result:

and this is the result when I first selected 3 checkboxes and then deselected with check box 2. ryzen 5

Share the news now

Source : Viblo