Sitemap

Use Ant Design Form with React Context API

2 min readApr 12, 2019

Ant Design is a popluar components framework for React. One of the components is <Form>. It provides built-in functions for collect, validate and submit user input.

<Form> in Ant Design is using a decorator pattern for the fields. This is not a problem until you want to separate the form and fields.

Here is an simple example.

It is just a simple login form. But when you have a more complex form or when you want to reuse a field, then you have to pass the form around to access the functionalities.

This become much cleaner. However, if it is not a single component but another large component, then, you will have to pass form through every components in the middle which is not ideal.

React Context API is the exact solution for what we needed.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

We can use <FormContext.Provider> and <FormContext.Consumer> but we have to do null checking and add form decorator every time. We can create a wrapper for those.

Those three pieces of code above are provider, consumer and React hook respectively. Then, we can refactor the form code.

Now, we no longer need to pass through form to each component. With Context API, it automatically use nearest parent provider. This means use do not need to update the fields to reuse them.

Originally published at joshuaavalon.io on April 12, 2019.

--

--

Avalon Joshua
Avalon Joshua

Written by Avalon Joshua

Average Developer, Data Hoarder, Homelabber

No responses yet