React: Dynamically Add input fields

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:

Prerequisites:

Step 1: Start by creating a react app.

STEP 2: Lets create creator polls container component

  • 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

  • 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store