Creating a responsive form with live updating using ReactJS and utilizing double inputs for better

Currently, I am working on updating a form with double input fields. The aim is for users to be able to click an 'add' button and update the state with their values, while ensuring that the two input fields are "connected". To better illustrate my goal, here is a graphical representation:

[input] [second input] [remove button]
[input] [second input] [remove button]
[input] [second input] [remove button] ...

Creating dynamic input fields becomes more challenging when dealing with two inputs. Although I have made progress in this direction, here is the current state of the code:

State:

stuff: {
        item: [],
        quantity: []
    }

This snippet demonstrates how I was able to dynamically add a single input field:

// Mapping 'stuff' due to changes in data structure
return this.state.stuff.map((element, index) => 
     <div key={index}>
         <input type="text" value={element||''} onChange={this.handleChange.bind(this, index)} />
         <input type='button' value='remove' onClick={this.removeInput.bind(this, index)}/>
     </div>          
 )

handleChange(index, event) {
    let stuff = [...this.state.stuff];
    stuff[index] = event.target.value;
    this.setState({ stuff });
}

add(){
    this.setState(previousState => ({ stuff: [...previousState.stuff,'']}))
}

removeInput(index){
    let stuff = [...this.state.stuff];
    stuff.splice(index,1);
    this.setState({ stuff });
}

I have been experimenting with different ideas, but I'm still puzzled by the addition of `''` in the `add()` function. Any insights or solutions that can help me achieve my intended functionality would be greatly appreciated.

Answer №1

I'm having trouble understanding how adding '' to the stuff array makes the code work.

If you examine your render() method, you'll notice this.state.stuff.map(...), where each value in the stuff array is mapped to the corresponding input. Therefore, by adding another value to stuff, the component will rerender and a new input will be mapped.


To add two inputs for each row, you could maintain two arrays, but this can complicate data management later on. Instead, I suggest using an array of objects with item and quantity properties. In the add() method, include new objects:

  this.setState(({ stuff }) => ({ stuff: [...stuff, { item: "", quantity: 0 }));

Then adjust your mapping within render() to display these objects:

 this.state.stuff.map(({ item, quantity }, index) => (
  <div>
   Item: <input value={item} onChange={e => this.update(index, "item", e.target.value)} />
   Quantity: <input value={quantity} onChange={e => this.update(index, "quantity", e.target.value)} />
  </div>
 ));

Lastly, create an update method that takes both an index and key to modify:

 update(index, key, value) {
   this.setState(({ stuff }) => ({ stuff: stuff.map((it, i) => i === index ? { ...it, [key]: value }, it)) }));
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which command in npm is used to generate a dist directory in Node.js?

I'm looking to set up my nodejs project (acting as a server for a react app) in a docker container, but I'm struggling to find an npm command that will generate a dist folder to include in the dockerfile. Any assistance would be greatly appreciat ...

Easy steps for importing node modules in TypeScript

I'm currently navigating the world of TypeScript and attempting to incorporate a module that is imported from a node module. I have chosen not to utilize webpack or any other build tools in order to maintain simplicity and clarity. Here is the struct ...

I can't seem to view my modal after increasing the number

Could you help me understand why my Modal is not appearing when I increase the number count? The counting functionality is working, but the Modal does not show up when the number increases. I would like the Modal to be displayed when the number is increm ...

Utilizing a single v-model for several elements

I am having an issue with a dropdown that is set to v-model="compose.Recipient". Based on the value of "compose.Recipient", I need another dropdown to appear as shown below: <div class="form-group" v-if="compose.Recipient==2" title="Select Class"> ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

Display loading spinner within Material-UI CardMedia

I am facing an issue with displaying a loader in CardMedia when the image is not loaded. Strangely, when I place the loader in CardText instead, it works fine and displays the loader as expected. Can someone help me identify what's wrong with my code ...

The setState function in React Native seems to be having trouble updating

I've been attempting to access state from a component, but for some reason, I'm not seeing any changes when I use setState(). Here is the current state of my component: class MyTestComponent extends React.Component { constructor(props){ ...

Design a clear button for MUI autocomplete feature

I'm currently working on a project where I need to implement a button that clears the MUI autocomplete value and removes the data from the UI. Although I've managed to delete the data from the UI with the code provided, the onChange value remain ...

The TypeORM connection named "default" could not be located during the creation of the connection in a Jest globalSetup environment

I've encountered a similar issue as the one discussed in #5164 and also in this thread. Here is a sample of working test code: // AccountResolver.test.ts describe('Account entity', () => { it('add account', async () => { ...

loading a module's dependencies seamlessly with RequireJS

Currently, I am working with Knockout and Require in my project. I have isolated some Knockout handlers into a separate module that I want to utilize. While there is no specific JavaScript code relying on this module, it is referenced in the data-bind attr ...

Tips for running a JavaScript function that is returned in an AJAX response

I am facing an issue with executing a function after a successful Ajax request in my jQuery code. Here is the snippet of my code: $.ajax({ type: "POST", url: "https://www.example.com/create_chat.php", data: dataString, beforeSe ...

Error: The login is invalid due to authentication failure with code 535 5.0.0

I'm currently working on setting up Outlook calendar events by integrating a mailing service with my project. I'm using the Express framework and Mongoose queries for this purpose. Below is the code snippet I have implemented: var _ = require(& ...

Looking for assistance with creating a D3 bar chart that involves selecting a specific year and crime category? Let me help

I am still learning D3 and I'm facing a challenge while trying to create a bar chart. My idea is to first select the YEAR radio button, then choose the CRIMEHEAD option, and finally the bar chart should be displayed. Here's my thought process: I ...

Having trouble with Discord.js version 12 and the messageReactionAdd event not triggering properly?

client.on('messageReactionAdd', (reaction, user) => { console.log('If you see this I actually work...'); }); I am having some trouble with my code. Despite setting up a simple console log, it seems like the code is not running prope ...

Unable to determine why node.js express path is not working

const express = require("express"); const app = express(); app.use(express.static("public")); var dirname = __dirname; app.get("/:lang/:app",function(req,res){ console.log(req.params.lang + " " + req.params.app); ...

Expanding box geometry from a single side in Three.js

Just starting out with three.js and my first task was to create a box geometry that could be increased from only one side. Issue : When increasing the width or height of an object, both sides automatically expand. Check out this jsFiddle Example I waste ...

What is the best way to determine the width of a CSS-styled div element?

Is there a way to retrieve the width of a div element that is specified by the developer? For example, using $('body').width() in jQuery will provide the width in pixels, even if it was not explicitly set. I specifically need to access the width ...

Shader customization and dynamic window resizing with Three.js

Having trouble with resizing the Three.js shader scene using ThreeX to handle window resizing and changing orientation on mobile devices. When the window width is decreased, everything works perfectly. However, expanding the window either in width or heigh ...

Convert a multidimensional array into a string using JavaScript

Currently, I'm in the process of generating an invoice for a collection of books and my intent is to submit it using ajax. However, when attempting to json encode the array of books within the invoice, I am encountering a setback where the value keeps ...