How to build a dynamic form in React using Hooks

An example of fully dynamic form rendering with Hooks and some other tricks

Hooks were added to React 16.8 and increased the number of features that can be used in functional components. The 2 main additions are lifecycle methods and state management.

The two hooks to achieve that are useEffect() and useState(). From these two I will use the latter to showcase state management in a dynamic form.

Let’s start by creating the first building block of our dynamic form, the Input.js component:

import React from "react";

import classes from “./Input.module.css”;

const Input = ({
text,
type,
placeholder = text,
handleChange,
name,
id = name,
required = false
}) => {
return (
<>
<label htmlFor={id}>{text}</label>
<input
className={classes.input}
required={required}
name={name}
id={id}
type={type}
placeholder={placeholder}
onChange={handleChange}
/>
</>
);
};

export default Input;

We are using couple of things here:

  • Css modules for styling. Thanks to the new react version no webpack configuration is necessary, React will recognize css modules if they are created with the module.css tag
  • Props destructuring for visibility and control over what props are we sending to our Input.js.
  • Setting default props, for instance placeholder = text. That means if we are not passing down a placeholder prop the text will be used as a default. Another benefit of props destructuring.

Secondly we should create our custom Button.js component:

import React from “react”;

import classes from “./Button.module.css”;

const Button = ({ text, clicked, buttonType }) => {
return (
<>
<button onClick={clicked} className={${classes.button} ${classes[buttonType]}}>
{text}
</button>
</>
);
};

export default Button;

Another trick we are using here:

  • We are passing the buttonType down, so that we can create custom styles for different type of buttons we want to have in the application, while classes.button provides the basic style. As Input.js, this component can also be further customized.

Now we have our Input.js and Button.js components, but before putting them to use we should create a file that will hold our input fields and form structures. Create the following file:

const fields = {
firstName: { type: “text”, name: “firstName”, text: “First Name”, placeholder: ‘Jack’, required: true },
lastName: { type: “text”, name: “lastName”, text: “Last Name”, placeholder: ‘Doe’, required: true },
email: { type: “email”, name: “email”, text: “Email”, placeholder: ‘jack@mail.com’, required: true },
addressLine: { type: “text”, name: “addressLine”, text: “Address Line”, placeholder: ‘Awesome str 9’, required: true },
postalCode: { type: “text”, name: “postalCode”, text: “Postal Code”, placeholder: ‘12345’, required: true },
city: { type: “text”, name: “city”, text: “City”, placeholder: ‘Gothenburg’, required: true },
state: { type: “text”, name: “state”, text: “State”, placeholder: ‘Gotaland’, required: true },
dob: { type: “date”, name: “dob”, text: “Date of Birth”, required: true },
password: { type: “password”, name: “password”, text: “Password”, required: true },
passwordConfrimation: { type: “password”, name: “passwordConfirmation”, text: “Password Confirmation”, required: true }
}

export const registerForm = [
fields.firstName,
fields.lastName,
fields.email,
fields.addressLine,
fields.postalCode,
fields.state,
fields.dob,
fields.password,
fields.passwordConfrimation
];

export const loginForm = [
fields.email,
fields.password
];

The fields object holds all possible field that we can add to our forms. This can be easily updated, new fields can be added or the current ones can be customized. I also added a registerForm and loginForm examples. We just need to export these arrays so that we can create the dynamic forms!

Next we will create the Form.js file where we will first use the useState() hook to manage the information in our form, and will also call all of those components we created to action!

import React from “react”;

import Input from “…/Input/Input”;
import Button from “…/Button/Button”;
import classes from “./Form.module.css”;

const Form = ({
formStructure,
formData,
setFormData,
formTitle,
buttonText,
onSubmit
}) => {
const handleChange = event => {
const formDataCopy = { …formData };
formDataCopy[event.target.name] = event.target.value;
setFormData(formDataCopy);
};
return (
<form className={classes.form} onSubmit={onSubmit}>
<h2>{formTitle}</h2>
{formStructure.map(f => (
<Input
key={f.name}
type={f.type}
name={f.name}
id={f.id}
text={f.text}
handleChange={handleChange}
placeholder={f.placeholder}
required={f.required}
/>
))}
<Button buttonType=‘primary’ text={buttonText} />
</form>
);
};

export default Form;

To break down what is happening here:

  • The formStructure prop is the array we export from formElements.js file, in this example either registerForm or loginForm. Since these are arrays we can use the map function to iterate through them and render the Input.js component. These objects hold all the information necessary for our Input.js component, so we just need to pass them down.
  • formTitle and buttonText are additional information either used in the Form.js itself or passed down to our custom Button.js component.
  • The last bit is the handleChange() function where we use useState() hook! Both formData and setFormData comes from the hook, however the state is not used in this form, but in the container that renders the form.
  • In the function we copy the formData using the spread operator. This is very important because the useState() hook — as opposed to this.setState() function does not automatically merge the state, but replaces it! Therefore we always have to preserve the previous state.
  • After copying we can set the object either create a new key or update the existing one by using this syntax: formDataCopy[event.target.name] = event.target.value

That is the basic skeleton for our dynamic form! Now we need a container to render it, where we have the actual logic: managing the state and performing the necessary side effects. I am going to show you an example for rendering registration and login form in a common container I call AuthenticationForm.js :

import React, { useState } from “react”;
import { connect } from “react-redux”;
import { withRouter } from “react-router-dom”;

import Form from “…/…/UI/Form/Form”;
import {
registerUser,
signInUser
} from “…/…/store/config/redux-token-auth-config”;

const AuthenticationForm = props => {
const [formData, setFormData] = useState({});
const action = data => {
switch (props.action) {
case “register”:
return props.registerUser(data);
case “login”:
return props.signInUser(data);
default:
console.log(“Something went wrong”);
}
};
const onSubmit = e => {
e.preventDefault();
action(formData)
.then(() => {
props.history.push(“/”);
})
.catch(error => {
console.log(error);
});
};

return (
<Form
onSubmit={onSubmit}
formTitle={props.formTitle}
setFormData={setFormData}
formStructure={props.formStructure}
formData={formData}
buttonText={props.buttonText}
/>
);
};

export default connect(
null,
{ registerUser, signInUser }
)(withRouter(AuthenticationForm));

You could create two separate components for registration and login forms, but there will be very little difference between them. In the name of re-usability and DRY code we will it in one container. So what is happening here?

  • const [formData, setFormData] = useState({}) is how we create our initial formData state, which is empty in the beginning, and setFormData() will be the function that will update that state.
  • The action function takes that formData and performs the selected function, which is either registerUser() or signInUser(). This is an authentication solution coming from redux-token-auth because we are using Rails as the API with devise-token-auth. During the function execution we use a switch statement where we can dynamically set that function based on the props we receive.
  • The last function is the onSubmit(), where we perform our action() function, making a HTTP POST request to our API. Upon success reroute to root using the react-router-dom package or catch errors (more error handling functions can be performed there).
  • As a side-note: the withRouter hoc is necessary because we are using the render() method in the <Route /> component (will be shown later), instead of the component prop. Because of that the history object is not available by default, we need to wrap the component with withRouter if we want to use it.

Finally we need to render the AuthenticationForm.js somewhere. I use the react-router-dom package to render the forms on different URLs in App.js:

import React, { lazy, Suspense } from “react”;
import { Route, Switch } from “react-router-dom”;

import Header from “./components/Header/Header”;
import { registerForm, loginForm } from “./UI/Form/formElements”;

const Fruits = lazy(() => import(“./components/Fruits/Fruits”));
const AuthenticationForm = lazy(() =>
import(“./components/AuthenticationForm/AuthenticationForm”)
);

const App = () => {
return (
<div>
<Header />
<Suspense fallback={<div>Loading …</div>}>
<Switch>
<Route exact path=“/” render={() => <Fruits />} />
<Route
exact
path=“/register”
render={() => (
<AuthenticationForm
action=“register”
formTitle=“Registration”
buttonText=“Register”
formStructure={registerForm}
/>
)}
/>
<Route
exact
path=“/login”
render={() => (
<AuthenticationForm
action=“login”
formTitle=“Login”
buttonText=“Login”
formStructure={loginForm}
/>
)}
/>
</Switch>
</Suspense>
</div>
);
};

export default App;

The loop is completed:

  • We import our registerForm and loginForm arrays from our formElements.js file which will create our dynamic forms.
  • We set the action prop which will determine which function will be used, registerUser() or signInUser().
  • We add the formTitle and buttonText to the forms.

The basic skeleton is ready for further use, after the little lengthy setup it will be much quicker and DRYer to create new forms in our application and without the need for Class components!

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

☞ Top 10 Custom React Hooks you Should Have in Your Toolbox

☞ How to Replace Redux with React Hooks and the Context API

☞ The Definitive React Hooks Cheatsheet

Originally published by Greg Kallai at https://medium.com

#reactjs #javascript #web-development

How to build a dynamic form in React using Hooks
223.90 GEEK