React: Dynamically Add input fields

Tanuj Choudhary
2 min readNov 17, 2020

--

In this tutorial I will show you how to add or remove input fields dynamically with React js. Sometimes the number of fields in a form are not predefined or they are different for every different users. So This tutorial will show how to do it the React way.

Example:

I was creating a live polling web app. Lets just see what the app does. There are creators and users. The creators create the poll. The users can vote the poll. So whenever a creator makes a poll. He has to submit a question for poll and several answers to be voted. Here the answers are not fixed. So we will see how to use React hooks to dynamically add answer fields as per the requirement.

Prerequisites:

Step 1: Start by creating a react app.

STEP 2: Lets create creator polls container component

  • Create a file CreatorPolls.jsx or anything according to your business problem.
  • Create fields object with question and answers key.
  • The answers will array of strings as number of answers fields will be changed.
  • Create a function that handles Input Change on field, Add Field and render fields.
  • Pass them as props to the view component.
  • Our Container component is ready. It handles all the logic for adding and handling input field.

STEP 3: Lets create creator polls View component

  • Lets see the view component.
  • Create a form.
  • It will contain a question field, answers field and a Add field button.
  • The logic will be handled by our container component.

This is how you can add fields dynamically using react. You can extract only add field logic from above code snippets and use it in your business problem.

That’s it.

Thanks for reading.

--

--