Replace item in array

I am trying to replace one element in my array with another element, I have a placeholder with a number on it, and when I click on add, the first element should go to the 1st position, the second element to the second position, etc.

At the moment, it will add an element to all positions when pressed, which is not the behavior that I would like.

If I delete the position number, I can get them to enter the array in the correct position, but I cannot get it to work with the placeholder.

How can I get a product item when I click on replace the position of a number in an array?

https://codesandbox.io/s/6z48qx8vmz

Hello.js

import React from 'react'; import update from 'immutability-helper' import styled from 'styled-components' import Product from './Product' const NumberWrap = styled.div` display: flex; flex-wrap:wrap border: 1px solid #ccc; flex-direction: row; ` const Numbers = styled.div` display:flex; background: #fafafa; color: #808080; font-size: 32px; flex: 0 0 20%; min-height: 200px; justify-content: center; align-items:center; border-right: 1px solid #ccc; ` const CardWrap = styled.div` display:flex; flex-wrap: wrap; flex-direction: row; margin-top: 20px; ` export default class Hello extends React.Component { constructor() { super() this.state = { placeholder: [1,2,3,4,5], data: [ { id: 1, header: 'Item 1'}, { id: 2, header: 'Item 2'}, { id: 3, header: 'Item 3'}, { id: 4, header: 'Item 4'} ], addedItems: [], } this.handleAdd.bind(this) this.handleRemove.bind(this) } handleAdd(id) { this.setState({ addedItems: update(this.state.addedItems, { $push: [ id, ], }) }) } handleRemove(index) { this.setState({ addedItems: update(this.state.addedItems, { $splice: [ [index, 1] ], }) }) } render() { return( <div> <NumberWrap> { this.state.placeholder.map(item => <Numbers>{item} { this.state.data.filter(item => this.state.addedItems.indexOf(item.id) !== -1).slice(0, 5).map(item => <Product {...item} remove={this.handleRemove} /> ) } </Numbers> )} </NumberWrap> <CardWrap> { this.state.data.map(item => <Product {...item} add={()=>this.handleAdd(item.id)} /> )} </CardWrap> </div> ) } } 

Product.js

 import React from "react"; import styled from "styled-components"; const Card = styled.div` flex: 0 0 20%; border: 1px solid #ccc; `; const Header = styled.div` padding: 20px; `; const AddBtn = styled.button` width:100%; height: 45px; `; const Product = props => { const { add, id, header, remove } = props; return ( <Card> <Header key={id}> {header} </Header> <AddBtn onClick={add}>Add</AddBtn> <AddBtn onClick={remove}>Remove</AddBtn> </Card> ); }; export default Product; 
+5
source share
1 answer

It was hard for me to understand the question, but is that what you want https://codesandbox.io/s/vj7vxw198y ? It will still take some work to add the same item multiple times if you want to.

+1
source

Source: https://habr.com/ru/post/1271561/


All Articles