kandi background
Explore Kits

Updating Values Inside an Array

by Abdul Rawoof A R Updated: Jan 24, 2023

In this kit, we're going to see how to update values inside an array using React with simple steps. Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in state. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array. To update an object in an array in React state: Use the map() method to iterate over the array. On each iteration, check if a certain condition is met. Update the object that satisfies the condition and return all other objects as is. To implement this, use the ready-made code snippet below by just copying the code and paste it in your IDE with required libraries.

Fig : Preview of the output that you will get on running this code from your IDE.

Code

In this solution we're using React library.

JavaScriptLines of Code : 141License : CC BY-SA 4.0

import React, { Component, Fragment } from "react";

export default class App extends Component {
  state = {
    items: [
      { id: "Apples", quantity: 0 },
      { id: "Strawberries", quantity: 0 },
      { id: "Grapes", quantity: 0 },
      { id: "Apricots", quantity: 0 }
    ]
  };

  handleChange = ({ target: { id, value } }) => {
    this.setState(prevState => ({
      items: prevState.items.map(item => {
        const nextVal = item.quantity + ~~value; // ~~ === parseInt(val, 10) -- required because the "value" is turned into a string when placed on a DOM element

        return id === item.id
          ? { id, quantity: nextVal > 0 ? nextVal : 0 }
          : { ...item };
      })
    }));
  };

  render = () => (
    <div className="container">
      <h1>Updating Values Inside Array</h1>
      {this.state.items.map(({ id, quantity }) => (
        <div key={id} className="container">
          <div>
            {id} ({quantity})
          </div>
          <button
            id={id}
            value={1}
            style={{ marginRight: 10 }}
            className="uk-button uk-button-primary"
            onClick={this.handleChange}
          >
            +
          </button>
          <button
            id={id}
            value={-1}
            style={{ marginRight: 10 }}
            className="uk-button uk-button-danger"
            onClick={this.handleChange}
          >
            -
          </button>
        </div>
      ))}
    </div>
  );
}

import React, { Component, Fragment } from "react";
import Button from "./button";

export default class App extends Component {
  state = {
    items: [
      { id: "Apples", quantity: 0 },
      { id: "Strawberries", quantity: 0 },
      { id: "Grapes", quantity: 0 },
      { id: "Apricots", quantity: 0 }
    ]
  };

  handleChange = (id, val) => {
    this.setState(prevState => ({
      items: prevState.items.map(item => {
        const nextVal = item.quantity + val;

        return id === item.id
          ? { id, quantity: nextVal > 0 ? nextVal : 0 }
          : { ...item };
      })
    }));
  };

  render = () => (
    <div className="container">
      <h1>Updating Values Inside Array</h1>
      {this.state.items.map(props => (
        <div key={props.id} className="container">
          <div>
            {props.id} ({props.quantity})
          </div>
          <Button
            {...props}
            className="uk-button uk-button-primary"
            handleChange={this.handleChange}
            value={1}
          >
            +
          </Button>
          <Button
            {...props}
            disabled={props.quantity === 0}
            className="uk-button uk-button-danger"
            handleChange={this.handleChange}
            value={-1}
          >
            -
          </Button>
        </div>
      ))}
    </div>
  );
}

import React, { PureComponent } from "react";
import PropTypes from "prop-types";

export default class Button extends PureComponent {
  static propTypes = {
    children: PropTypes.string.isRequired,
    className: PropTypes.string,
    disabled: PropTypes.bool,
    id: PropTypes.string.isRequired,
    handleChange: PropTypes.func.isRequired,
    value: PropTypes.number.isRequired
  };

  handleClick = () => {
    this.props.handleChange(this.props.id, this.props.value);
  };

  render = () => (
    <button
      disabled={this.props.disabled || false}
      className={this.props.className}
      onClick={this.handleClick}
      style={{ marginRight: 10 }}
    >
      {this.props.children}
    </button>
  );
}

Instructions

Follow the steps carefully to get the output easily.

  1. Install the Node.js and React on your IDE(preferable Visual Studio Code).
  2. Create React Application using npx create-react-app foldername.
  3. cd foldername.
  4. Install npm i uikit.
  5. Open the folder in IDE.
  6. Copy the code using "copy" button above then create a file in the name of UpdateQuantity.js and paste it in that UpdateQuantity.js file.
  7. Import UpdateQuantity.js file in index,js file(also refer demo given below).
  8. Open the terminal from IDE.
  9. npm start to run the file.


You can also refer this url 'DEMO' for getting the above output.

I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for 'react interview exercise' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in Visual Studio Code 1.73.1.
  2. The solution is tested on node v18.12.1 and npm v8.19.2.
  3. React version-18.2.0.
  4. Uikit version-current.


Using this solution, we are able to update values inside an array in React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to update values inside an array in React.

Dependent Libraries

reactby facebook

JavaScript star image 201119 Version:18.2.0

License: Permissive (MIT)

A declarative, efficient, and flexible JavaScript library for building user interfaces.

Support
Quality
Security
License
Reuse

reactby facebook

JavaScript star image 201119 Version:18.2.0 License: Permissive (MIT)

A declarative, efficient, and flexible JavaScript library for building user interfaces.
Support
Quality
Security
License
Reuse

uikitby visionmedia

JavaScript star image 1321 Version:0.0.4

License: Others (Non-SPDX)

UIKit - modern ui components for the modern web

Support
Quality
Security
License
Reuse

uikitby visionmedia

JavaScript star image 1321 Version:0.0.4 License: Others (Non-SPDX)

UIKit - modern ui components for the modern web
Support
Quality
Security
License
Reuse

You can also search for any dependent libraries on kandi like 'react' and 'uikit'.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.


See similar Kits and Libraries

JavaScript
User Interface