screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState } = React; function App() { // Sample state with an array of objects const [items, setItems] = useState([ { id: 1, name: 'Laptop' }, { id: 2, name: 'Mouse' }, { id: 3, name: 'Keyboard' }, { id: 4, name: 'Monitor' }, { id: 5, name: 'Headphones' }, { id: 6, name: 'Speakers' }, // Add more items here ]); // Function to move an item one position up const moveUp = (index) => { if (index > 0) { // Clone the original array const clonedItems = [...items]; // Swap the item with the one before it const temp = clonedItems[index - 1]; clonedItems[index - 1] = clonedItems[index]; clonedItems[index] = temp; // Update the state with the modified array setItems(clonedItems); } }; // Function to move an item one position down const moveDown = (index) => { if (index < items.length - 1) { // Clone the original array const clonedItems = [...items]; // Swap the item with the one after it const temp = clonedItems[index + 1]; clonedItems[index + 1] = clonedItems[index]; clonedItems[index] = temp; // Update the state with the modified array setItems(clonedItems); } }; return ( <div className='container'> <h3 className='title'>React Js Change objects position in array</h3> <ul> {items.map((item, index) => ( <li key={item.id} className='list-item'> {item.name} <button className='move-up-button' onClick={() => moveUp(index)} disabled={index === 0} // Disable if it's the first item > Move Up </button> <button className='move-down-button' onClick={() => moveDown(index)} disabled={index === items.length - 1} // Disable if it's the last item > Move Down </button> </li> ))} </ul> </div> ); } ReactDOM.render(<App />, document.getElementById('app')); </script> <style> /* Style the container */ .container { max-width: 600px; margin: 0 auto; padding: 20px; text-align: center; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); } .title { font-size: 24px; margin-bottom: 20px; text-align: center; color: #333; } ul { list-style-type: none; padding: 0; } .list-item { background-color: #fff; padding: 10px; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; } .list-item button { background-color: #007bff; color: #fff; border: none; border-radius: 3px; padding: 5px 10px; cursor: pointer; transition: background-color 0.2s; } .list-item button:hover { background-color: #0056b3; } .move-up-button { margin-right: 10px; } .move-down-button { margin-left: 10px; } </style> </body> </html>