score:1
Once you've found the index of the key in selectedItems
, set selectedItems
's state by slicing the array before and after that index:
const index = selectedItems.indexOf(key);
setSelectedItems([
...selectedItems.slice(0, index),
...selectedItems.slice(index + 1)
]);
const { useState } = React;
const App = () => {
const [selected, setSelected] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
const [cards, setCards] = useState(["card1", "card2", "card3", "card4"]);
function handleButtonClick(event) {
setSelected(true);
let key = event.target.id;
key = parseInt(key, 10);
if (selectedItems.indexOf(key) === -1) {
let index = selectedItems.indexOf(key);
setSelectedItems([...selectedItems, key]);
} else {
const index = selectedItems.indexOf(key);
setSelectedItems([
...selectedItems.slice(0, index),
...selectedItems.slice(index + 1)
]);
}
}
return (
<div className="App">
{cards.map((card, index) => (
<button
className={
selected && selectedItems.indexOf(index) !== -1
? "button1 active"
: "button1"
}
onClick={handleButtonClick}
id={index}
key={index}
>
{card}
</button>
))}
</div>
);
}
ReactDOM.render(<App />, document.querySelector('.react'));
.App {
font-family: sans-serif;
text-align: center;
}
.active {
border: 2px solid green;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>
Also remember to use a unique key
prop for lists, and to prefer const
over let
whenever possible.
score:0
I find it odd that the simple, standard answer hasn't been posted:
function handleButtonClick(event) {
setSelected(true);
const key = parseInt(event.target.id, 10);
setSelectedItems(selectedItems => {
const itemIndex = selectedItems.indexOf(key);
if (itemIndex === -1) {
// New item, add it
selectedItems = [...selectedItems, key];
} else {
// New item, add it
selectedItems = selectedItems.filter((_, index) => index !== itemIndex); // ***
}
return selectedItems;
});
}
Notice that since this sets state based on existing state, it's best to use the callback form of the state setter.
score:1
Use this one. Hope it will work.
if (selectedItems.indexOf(key) === -1) {
setSelectedItems([...selectedItems, key]);
} else {
// HOW do i remove the item from the array ????
let index = selectedItems.indexOf(key);
const arr = selectedItems.filter((item, i) => i !== index);
setSelectedItems(arr);
}
Check this link https://codesandbox.io/s/stupefied-greider-m25le
score:1
You can make a copy of your array, splice the index from the copy then set the state with the new array.
const newArray = [...oldArray]
newArray.splice(index, 1)
setSelectedItems(newArray)
score:1
An alternative to @CertainPerformance using splice
:
const copy = [...selectedItems];
const index = copy.indexOf(key);
copy.splice(index, 1);
setSelectedItems(copy);
score:1
An option using Array#splice
that uses the function form of setState
:
const [items, setItems] = React.useState([]);
const deleteItemAtIndex = (index) => setItems(items => {
const newItems = [...items];
newItems.splice(index, 1);
return newItems;
});
This has the advantage that it can be memoized (useCallback
) without needing items
as a dependency (since setItems
is always stable and the function itself doesn't use items
, only the callback does):
const deleteItemAtIndex = React.useCallback((index) => setItems(items => {
const newItems = [...items];
newItems.splice(index, 1);
return newItems;
}), []);
Source: stackoverflow.com
Related Query
- React.js remove item from Array in state syntax
- React remove item from array state doesnt re render
- React JS: how to properly remove an item from this.state.data where data is an array of objects
- Remove first item of array in react state
- Remove item from array in React
- Remove element of an object from array of objects - react state
- how to pass the current item to the function so that i can remove it from array in react component?
- How to add & remove item from reducer state in react
- Remove object by id from array in React hooks state
- Error rendering item from state array in React
- How to remove item from a generic Array in React Typescript?
- How to remove item from an array through index in React
- Deleting item from state array in react
- React - Remove item from array using its name / value
- Update state array in React JS with item from Smart Contract
- Cannot retrieve single item from an array stored in the state of React
- How to delete an item by index from a state array in React
- React Hooks Remove item from array
- React hooks - Remove multi object from array and update state
- How to remove specific item from react state
- react remove item from array of object
- React - How do I remove array item from state?
- React Select Unable to Remove Items From State Array
- Trying to move an item from one array to another in React state
- How remove item from redux state using react hooks
- remove last item from array and rerender in react failed
- How to remove item from array stored in localstorage if the item already exists and changing state of button
- Remove node and replace with item from an array into the same node location with React
- Redux wont remove item from state array by ID
- Remove empty items from my array and remove selected item when checkbox checked in react
More Query from same tag
- Simplify filter js
- Trying to access a custom prop in styled components
- Linking to a component from the same component doesn't work
- How to correctly format date with timezone in date-fns?
- How to enable and disable p tag in react when certain condition passes
- React-Bootstrap causing margins on left and right side
- React setState can only update a mounted or mounting component
- send the data in the request
- (React) How can I stop my web app from re-rendering when I fetch some data from an API?
- React Passing props to background url in template literal
- Tags are closed but compiler throws "Parsing error: Expected corresponding JSX closing tag for <img>"
- JS, React - calculate height of dynamically created area with div blocks
- React router activeClassName doesnt set active class for child routes
- React custom modal display modal content for milliseconds while refreshing page
- Is there a way to set the initial value for React Google Places AutoComplete?
- Why is React-Testing-Library / Jest receiving DOM input backwards?
- Express server serves my static files but does not handle requests to my API. What is happening?
- How to read data from axios response through module.exports?
- NextJS/Django Manually Typing in URLs
- @twilio/flex-webchat-ui how to integrate in my react redux project
- Filtering Mapped React Table Data with JSON Data
- CSS in ReactJS - media query and grouping selectors
- React router not open 404 not found page
- React: why set the document title inside useEffect?
- How to display multiple varied states for multiple radio groups?
- How to over-ride React-Table default sort for date formats like 'MM-DD-YYYY' (07-22-2021)?
- Minimal react-dnd hooks example breaks on "Expected drag drop context"
- React - How do I use a handleInputChange function to change a state value that is within a state value?
- Is it a good practice to use getter to render another component inside React component?
- Access data from onmessage function from a websocket in Reactjs