Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to submit dynamically created textbox value on button click in ReactJS

Introduction To ReactJS

ReactJS is a JavaScript library that is used for building user interfaces, specifically for single-page applications. It’s used for handling the view layer for web and mobile apps. It allows you to design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.

Think of it like building a Lego set. Each individual piece of Lego (which we'll call components) has a specific job and can be used in different models. This is similar to how ReactJS works. Each component has a specific job and can be used in different parts of your application.

Understanding The Problem

Now, let's say we have a scenario where we need to create text boxes dynamically in our ReactJS application and collect the values entered by the user when a button is clicked.

This might seem like a daunting task at first, especially if you are just starting out with ReactJS. However, with the right mindset and a step-by-step approach, it becomes a lot easier.

Breaking Down The Problem

A good strategy to solve this problem is to break it down into smaller tasks:

  1. Create a button to add text boxes dynamically.
  2. Create a text box in ReactJS.
  3. Store the user's input from the text box.
  4. Create a button for submission.
  5. Capture the data from the text boxes when the submit button is clicked.

Creating a Button to Add Textboxes Dynamically

In ReactJS, creating a button is as simple as creating a 'button' element. The onClick attribute is added to the button element to listen for a click event.

Here's an example:

<button onClick={this.addTextBox}>Add Text Box</button>

In the above example, addTextBox is a method that gets called every time the button is clicked. This method will handle the creation of the text boxes.

Creating a Text Box in ReactJS

A text box in ReactJS can be created by using the 'input' element and setting the type attribute to 'text'.

Here's a simple example:

<input type='text' />

Storing the User's Input from the Text Box

In order to store the user's input from a text box, we need to add an onChange attribute to the input element. The onChange attribute calls a method every time the value of the text box changes.

Here's an example:

<input type='text' onChange={this.handleInputChange} />

In the above example, handleInputChange is a method that gets called every time the value of the text box changes.

Creating a Button for Submission

Creating a submission button follows the same principle as creating the button to add text boxes. The only difference is that the method it calls when clicked will be responsible for handling the submission of the data.

Here's an example:

<button onClick={this.handleSubmit}>Submit</button>

Capture the Data from the Text Boxes When the Submit Button is Clicked

To capture the data from the text boxes when the submit button is clicked, we need to store the values of the text boxes in the state of the component. Then, when the submit button is clicked, we can access the current state and get the values of the text boxes.

Here's an example:

handleSubmit = () => {
    const { textBoxValues } = this.state; // get the text box values from the state

    // handle the submission of the text box values
}

In the above example, handleSubmit is the method that gets called when the submit button is clicked.

Putting It All Together

Now that we have broken down the problem into smaller tasks, let's put it all together.

Here's a simple ReactJS component that implements the functionality we just described:

class MyComponent extends React.Component {
    state = {
        textBoxes: [], // to keep track of the text boxes
        textBoxValues: {} // to keep track of the text box values
    }

    addTextBox = () => {
        this.setState(prevState => ({
            textBoxes: [...prevState.textBoxes, '']
        }))
    }

    handleInputChange = (e, index) => {
        this.setState(prevState => ({
            textBoxValues: {
                ...prevState.textBoxValues,
                [index]: e.target.value
            }
        }))
    }

    handleSubmit = () => {
        const { textBoxValues } = this.state;

        // handle the submission of the text box values
        console.log(textBoxValues);
    }

    render() {
        const { textBoxes } = this.state;

        return (
            <div>
                {textBoxes.map((textBox, index) => (
                    <input 
                        key={index} 
                        type='text' 
                        onChange={e => this.handleInputChange(e, index)} 
                    />
                ))}
                <button onClick={this.addTextBox}>Add Text Box</button>
                <button onClick={this.handleSubmit}>Submit</button>
            </div>
        )
    }
}

In this example, we first initialize our state with two empty arrays, one for the text boxes and one for their values. Every time the 'Add Text Box' button is clicked, a new text box is added to the textBoxes array. The handleInputChange method is responsible for updating the textBoxValues state with the current value of each text box. Finally, when the 'Submit' button is clicked, the handleSubmit method is called, which simply logs the current state to the console.

Conclusion

ReactJS provides a powerful way to handle user input and form submission. By breaking down the problem into smaller tasks, we have seen how to create text boxes dynamically, capture the user's input and handle the submission of the form. With this knowledge, you can now create more complex forms and handle user input in your ReactJS applications.