How to implement a dynamic form with controlled components in ReactJS?

Asked
Active3 hr before
Viewed126 times

7 Answers

controlledcomponentsreactjsimplementdynamic
90%

2- Array to store the values of each input element separately.,Connect and share knowledge within a single location that is structured and easy to search.,I did it in the render method just to be clear but all the logic can be moved in auxiliary functions.,Maintain an array inside state, that will store the values. Use #array.map to create ui (input element) for each array values. while creating the fields, use a remove button with each field, and pass the index of field in that function, it will help you to identify which field you wants to delete, do the same thing for onChange also.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { values: [] };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  createUI(){
     return this.state.values.map((el, i) => 
         <div key={i}>
    	    <input type="text" value={el||''} onChange={this.handleChange.bind(this, i)} />
    	    <input type='button' value='remove' onClick={this.removeClick.bind(this, i)}/>
         </div>          
     )
  }

  handleChange(i, event) {
     let values = [...this.state.values];
     values[i] = event.target.value;
     this.setState({ values });
  }
  
  addClick(){
    this.setState(prevState => ({ values: [...prevState.values, '']}))
  }
  
  removeClick(i){
     let values = [...this.state.values];
     values.splice(i,1);
     this.setState({ values });
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.values.join(', '));
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
          {this.createUI()}        
          <input type='button' value='add more' onClick={this.addClick.bind(this)}/>
          <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container' />
load more v
88%

There’s a bit of state that we’re going to have to manage in the React components, such as which page of the form we’re on and the values of the Controlled Components. For this, we’ll use Hooks so that we can stick with function components.,With the values now available to the Controlled Components, all that’s left is creating a function to update them.,This will render out a label and input in a basic manner, update the HTML to the structure that’s required for your design (or render out fields from a form library like Formik). The two props that are likely to be of most interest as the value and fieldChanged. The value prop is the current value for the Controlled Component, which will come from the Form component itself (we’ve not implemented that yet) and fieldChanged will be used to update this main state list.,The structure we’ve got here is intended to be simple. It is made from an array of pages, with each page identified by the component value of page, and within that is an array of fields that contains the inputs, or groups of inputs (again, denoted by the component property).

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
load more v
72%

React makes building UI’s in JavaScript easy, but some things can still be a bit tricky to wrap your head around, things like dynamic forms. A dynamic form is one where the user is able to decide how many inputs there should be. For this code along, we’re going to have standard inputs for a cat owner’s name and a short description, and then dynamically add cat inputs. Each new cat will have a name and age, just for fun.,That may take a second to get comfortable with, but by making our change handler dynamic, we can put it on the whole form instead of each input:,There you have it! A basic run through of making a dynamic form in react. Follow this basic pattern as a jumping off point for your next project, and try to find some parts to streamline once you understand the process.,Planning is crucial with React, it can save you so much time if you wireframe out what you want before you start coding. We know what it will look like, but how will it be made? I like to have a little React checklist:

Now for the fancy part; handling our dynamic inputs. First, we’re checking whether the event’s class matches our dynamic inputs. If it does, we make a copy of our cats array of objects using the spread operator. Now it gets real fancy. We use e.target’s dataset to match the input to its corresponding object, and then we use the e.target’s classname to grab either the cat object’s name or age value. So, if a user types into the first cat name input this is what it would translate to:

cats[e.target.dataset.id][e.target.className] = e.target.value // cats[0][name] = whatever-was-typed
load more v
65%

We’ll be illustrating dynamic form fields in React using a simple form that has two input fields. One for the first name and another for the last name, these would form the user data. These two fields would be dynamically duplicated to create more fields that are unique and can accept new user data.,Update the input fields to include a change handler to cater for user input action. See the change below: ,Using React Hooks, initialise the form input fields like so: ,In the above snippet, inputFields refers to the form fields, while setInputFields is the used to set the value for these form fields

npx create - react - app my - app
cd my - app
npm start
load more v
75%

The example app component contains all the code for the dynamic form built with React Hook Form.,This is a quick example of how to build a dynamic form with validation in React with the React Hook Form library.,Form validation rules are defined with the Yup schema validation library and passed to the useForm() function of the React Hook Form library., React - Form Validation Example with React Hook Form

0
40%

An extensible set of base components to create custom components that aren't available in Formik (ex: datepicker),Formik - Injects a context called FormikContext into the child components. This is where the form state is saved. All child components can now access it using the useFormikContext hook.,A consistent API across most form elements,With the above set, you can next put these into a React form and test the functionality. The following code shows how to create a basic form on the above elements. The code is quite clean in comparison to using bare metal form elements.

1// FormElements.jsx
2
3import React from 'react';
4import {
5    Formik,
6    Form as FormikForm,
7    Field,
8    ErrorMessage,
9    useFormikContext,
10    useField,
11    useFormik
12} from 'formik';
13
14export function Form(props) {
15    return (
16        <Formik
17            {...props}
18        >
19            <FormikForm className="needs-validation" novalidate="">
20                {props.children}
21            </FormikForm>
22        </Formik>)
23}
24
25export function TextField(props) {
26    const { name, label, placeholder, ...rest } = props
27    return (
28        <>
29            {label && <label for={name}>{label}</label>}
30            <Field
31                className="form-control"
32                type="text"
33                name={name}
34                id={name}
35                placeholder={placeholder || ""} 
36                {...rest}
37            />
38            <ErrorMessage name={name} render={msg => <div style={{ color: 'red' }} >{msg}</div>} />
39        </>
40    )
41}
42
43export function SelectField(props) {
44    const { name, label, options } = props
45    return (
46        <>
47            {label && <label for={name}>{label}</label>}
48            <Field
49                as="select"
50                id={name}
51                name={name}
52            >
53                <option value="" >Choose...</option>
54                {options.map((optn, index) => <option value={optn.value} label={optn.label || optn.value} />)}
55            </Field>
56            <ErrorMessage name={name} render={msg => <div style={{ color: 'red' }} >{msg}</div>} />
57        </>
58    )
59}
60
61export function SubmitButton(props){
62    const { title, ...rest } = props;
63    const { isSubmitting } = useFormikContext();
64    
65    return (
66        <button type="submit" {...rest} disabled={isSubmitting}>{title}</button>
67    )
68}
load more v
22%

Implement logic to add/remove fields,Set focus on the dynamic input field in React,ReactJSSet focus on the dynamic input field in React, Add or remove input fields dynamically with ReactJS

load more v

Other "controlled-components" queries related to "How to implement a dynamic form with controlled components in ReactJS?"