Dynamically Generate Responsive Form Fields in React

Every once in a while, there’s a form to be built. Every so often, that form needs to be dynamic. Whether the form is dynamic or static, it always needs to be responsive.

The Problem

On a recent software development project, my task was to create a form with three columns visible on a large window (such as a desktop). It should reduce to two columns on a smaller window (such as a tablet, maybe) and further decrease to a single-column form on a small screen like a mobile device.

Responsive Form Fields

We start by looping over our set of fields and generating each one dynamically. For each form field, we return a Col component which is a part of Bootstrap’s responsive grid system.


{fields.map((entry: FormField, index) => {
    const value = data[entry.key];
    return (
      
{/* Inline code goes here */}
); })}

The Col component’s props determine how it should behave at different widths. For example, the xs={12} prop means that on extra small screens, the column should occupy the entire width.

md and lg determine the behavior at medium and large screen widths respectively. md is set conditionally to either occupy the full width (12 columns) or half the width (six columns, for two form fields side by side). This behavior is based on the numberOfColumns variable, which you should update based on your needs.

Within each Col component, I’ve created a Form.Group that encapsulates the actual form field. We pass its label, the value, the onChange function among other props to a DynamicFormField component, which is responsible for rendering the correct kind of input field.


< Form.Group key={index} controlId={entry.label} className='mb-3' >
  < Form.Label>{entry.label}< /Form.Label>
  < DynamicFormField {/* Props here */} />
< /Form.Group> 

The DynamicFormField component should ideally be able to render different types of form fields based on the provided props. You can specify the different kinds of fields the form can generate by creating your own enum for types, i.e.: string | text | dropdown | checkbox

In conclusion, React and Bootstrap’s grid system combined provide a powerful toolset to create forms that dynamically adapt their layout to different screen sizes.

Examples

Here is what a simple form could look like on three different screen sizes.

With just a few lines of code, you can achieve a responsive, multi-column layout which is especially important in the current digital age where accessing websites from different devices is the norm.

Conversation
  • Solar says:

    Thanks for the helpful advice. Much appreciated!

  • Join the conversation

    Your email address will not be published. Required fields are marked *