[Edit]
+
0
-
0
React - append, prepend, remove and replace items in array in useState() using utils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64// Note: // // The below utils can be used to simplyfy operation on React states when we want to use array as state. const prependItem = (updater, item) => { updater(array => [].concat(item, array)); }; const appendItem = (updater, item) => { updater(array => [].concat(array, item)); }; const replaceItem = (updater, index, item) => { updater(array => array.map((value, i) => i === index ? item : value)); }; const removeItem = (updater, index) => { updater(array => array.filter((value, i) => i !== index)); }; // ------------------------------------------------------------ // Usage example: // ------------------------------------------------------------ import React from 'react'; import ReactDOM from 'react-dom'; let counter = 0; const App = () => { const [array, setArray] = React.useState([]); const handlePrependClick = () => prependItem(setArray, (++counter) + '-prepended'); const handleAppendedClick = () => appendItem(setArray, (++counter) + '-appended '); return ( <div> <div> <button onClick={handlePrependClick}>Prepend</button> </div> <br /> <pre style={{border: '1px solid silver'}}> {array.map((item, index) => { const handleReplaceClick = () => replaceItem(setArray, index, (++counter) + '-replaced '); const handleRemoveClick = () => removeItem(setArray, index); return ( <div> <span>{item}</span> {' '} <button onClick={handleReplaceClick}>Replace</button> <button onClick={handleRemoveClick}>Remove</button> </div> ); })} </pre> <br /> <div> <button onClick={handleAppendedClick}>Append</button> </div> </div > ); }; export default App;
Reset