score:1
you need to pass the remove function to product
component, in product
component pass the select and index to removeitem
function.
modify your remove item, to take in two parameters, select
and index
.
removeitem = (select, index) => {
const filtered = this.state.products[select].colors.filter(
(color, i) => i !== index
);
this.setstate(prevstate => {
return {
select: select,
index: index,
products: [
...prevstate.products.slice(0, select),
object.assign({}, prevstate.products[select], { colors: filtered }),
...prevstate.products.slice(select + 1)
]
};
});
};
pass the function as prop to product
component.
<div>
<ul>
{this.state.products.map((product, index) => (
<product
key={index}
index={index}
removeitem={this.removeitem}
product={product}
/>
))}
</ul>
</div>
in your product component, pass the index of the color and the select.
<button onclick={() => removeitem(index, i)}>x</button>
demo
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
class product extends react.component {
render() {
const { product, removeitem, index } = this.props;
return (
<div>
<p>{product.desc}</p>
<ul>
{product.colors.map((color, i) => (
<li>
{color.a} <button onclick={() => removeitem(index, i)}>x</button>
</li>
))}
</ul>
</div>
);
}
}
class app extends react.component {
constructor() {
super();
this.state = {
name: "react",
products: [
{
colors: [{ a: "black" }, { a: "orange" }, { a: "purple" }],
desc: "gfgfg"
},
{
colors: [{ a: "yellow" }, { a: "white" }, { a: "gray" }],
desc: "gfgfgfg"
},
{
colors: [{ a: "pink" }, { a: "brown" }, { a: "green" }],
desc: "gfgfgfg"
}
],
select: 1, //example
index: 1 //example
};
}
removeitem = (select, index) => {
const filtered = this.state.products[select].colors.filter(
(color, i) => i !== index
);
this.setstate(prevstate => {
return {
select: select,
index: index,
products: [
...prevstate.products.slice(0, select),
object.assign({}, prevstate.products[select], { colors: filtered }),
...prevstate.products.slice(select + 1)
]
};
});
};
render() {
return (
<div>
<ul>
{this.state.products.map((product, index) => (
<product
key={index}
index={index}
removeitem={this.removeitem}
product={product}
/>
))}
</ul>
</div>
);
}
}
reactdom.render(<app />, document.getelementbyid("root"));
</script>
score:0
just use array.filter()
to create a new array not containing the specific element. so your new color array for that desc is:
this.state.products[select].colors.filter( color => color.a !== 'orange' )
this keeps all the colors where a
is not orange.
keep in mind that arrays are zero-based, so your select
and index
should both start at 0.
if you do not want to store the actual indexes, use the desc instead.
so if select
would be gfgfg
instead of the array index, you could do:
const state = {
products: [
{
colors: [{a:'black'}, {a:'orange'}, {a:'purple'}],
desc: 'gfgfg'
},
{
colors: [{a: 'yellow'}, {a: 'white'}, {a:'gray'}],
desc: 'gfgfgfg'
},
{
colors: [{a: 'pink'}, {a: 'brown'}, {a:'green'}],
desc: 'gfgfgfg'
}
],
selected_product: 'gfgfg',
color: 'orange'
};
const setstate = update => object.assign( state, update );
console.log( 'before update' );
console.log( json.stringify( state.products[0] ));
setstate({
products: state.products.map( product => {
if ( product.desc === state.selected_product ) {
product.colors = product.colors.filter( color => color.a !== state.color );
}
return product;
})
});
console.log( 'after update' );
console.log( json.stringify( state.products[0] ));
same logic can obviously be done using the indexes, but that might result in longer code. might have to update some of the code if everything has to be fully immutable.
Source: stackoverflow.com
Related Query
- How delete an object based on its index from a nested array in React?
- How to delete object from array using object property - React
- How to delete an item by index from a state array in React
- How to create Material-UI nested style object from array using map in React
- How to set defaultValue of a radioGroup from a nested Array object in React state?
- How can I show certain elements from an array based on a React State?
- How to remove an element from an array that is inside an object in React JS (ES6)
- How to use an object to delete it from objects array javascript?
- How to delete objects from react state hook array with a button click
- How to select random object from array with React Hooks?
- How to access previous index route in nested routes using Link component from react router?
- How to remove selected index of an array from the DOM and reflect the change in React state?
- how to delete nested object in React with spread function
- How can I render the contents of an array nested inside an object in React Admin's show/ArrayField component?
- How to find most recent date from an array of object then add new field and return array in react
- How Can i Add Event Handlers In Reusable React Component Created from Object Array
- How can I render data from array nested in object from API in React?
- How to get nested Object from JSON File using React JS
- How to add new element to array which inside nested object by its path?
- How to add a deeply nested object to a deeply nested Array in a React Reducer?
- How to use spread operator to delete an object from array of objects using spread operator using react?
- How to remove item from an array through index in React
- How to remove Object from Array based on ID in react?
- How to remove a single object from Array Properties in React Js?
- How to push nested object interface array in React Typescript using useState
- How To Send Array of Object using FormData() From React Js To Nodejs, MongoDB?
- How to return an object property from an array of objects in react
- React-Redux update state of immutable object with nested array, delete element from array
- How to access nested array object in React
- React - How to Push an Object to an Array Nested within an Array
More Query from same tag
- React useContext() default value has not changed even I provide a value
- How to get id from url (react-router-dom v 6) for class component ReactJS (v 18)
- How to test React ErrorBoundary
- Take keys from another property
- How do I display data fetched from firestore to a boostrap table in reactjs? I'm able to fetch but cannot display with the standard way of doing it
- Rails 404 not found for existing user
- React JS auto complete functions
- Adding the labels to the react-select
- Routes not working as desired in React JS
- How to get an component height to trigger Headroom in React?
- How to put data inside a customize state in for loop in functional component
- How to modify an array's each object's properties based on another array in React/JS?
- Pass the element itself as an onClick parameter instead of an instance of a class
- react className conditional setting according to all of state
- How can i dry up this react/material ui code?
- React Antd v4 autocomplete shows selected value instead of label upon selecting an option
- Pass value and use as object properties dynamically in Javascript
- React-Redux: Forms in component or container?
- React Flowtype Node.contains() Event Target
- React not updating component when performing deep updates of props
- React Material-UI with Router
- Change folder of "next export"
- How to read and modify Object passed to a function in React
- Error: An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft
- const { authenticated } = this.props is undefined though I can clearly see it in redux
- Targeting a class element node inside react function of createElement() class
- React is rendering before api data arrived
- Styling react-router-dom Link using styled-components getting warning when passing props
- React set scroll position before component mount
- LocalStorage keeps changing my key-pair instead of pushing to the array