I have this array that is formed from strings that I map through jsx and I want whenever a specific element is clicked to disappear by being removed from the array.
I tried achieving this by using slice()
but I am doing something wrong and I would appreciate if you could help me.
This is how I tried to approach it.
export default function App() {
const arr = ['string1', 'string2', 'string3', 'string4', 'string5', 'string6']
const removeMe = (index) => {
if(index > -1) {
arr.slice(index, 1);
}
return arr;
}
return (
<div className="App">
{arr.map((string, index) => (
<button
key={`string${index}`}
onClick={() => removeMe(index)}
>
{string}
</button>
))}
</div>
);
}
Also, here is a codeSandBox if it helps.
CodePudding user response:
For this you have to use useState hook. Refer this link. It have a example which is simmilar to your code.
https://reactjs.org/docs/hooks-state.html
To rerender a component state or props must change.useState hooks use for change state.
CodePudding user response:
First of all you will need a state (using useState hook) for array in order for React to be able to re-render whenever that state changes so you need to add the following line:
const [arr, setArr] = React.useState(['string1', 'string2', 'string3', 'string4', 'string5', 'string6'])
Regarding the removal problem:
Multiple solutions would be possible. Important is to always return a new array instance:
- Use
filter()
const removeMe = (index) => setArr(arr.filter((_, i) => i !== index));
- Use splice()
const removeMe = (index) => {
const temp = [...arr]
temp.splice(index, 1)
setArr(temp)
}
Here what your component might look like:
function App() {
const [arr, setArr] = React.useState(['string1', 'string2', 'string3', 'string4', 'string5', 'string6'])
const removeMe = (index) => setArr(arr.filter((_, i) => i !== index));
return (
<div className="App">
{arr.map((string, index) => (
<button
key={`string${index}`}
onClick={() => removeMe(index)}
>
{string}
</button>
))}
</div>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>
CodePudding user response:
Here you go. Use React state and the according setter to overwrite the modified array values.
Also note the usage of arrow function with implicit return.
import { useState } from 'react'
export default function App () {
const [arr, setArray] = useState([
'string1',
'string2',
'string3',
'string4',
'string5',
'string6'
])
const removeMe = index => setArray(arr.filter((_, i) => i !== index))
return (
<div className='App'>
{arr.map((string, index) => (
<button key={`string${index}`} onClick={() => removeMe(index)}>
{string}
</button>
))}
</div>
)
}