screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div id="app"></div> <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> <script type="text/babel"> const { useState } = React; const initialData = [ { name: 'John', age: 30, score: 85 }, { name: 'Alice', age: 25, score: 90 }, { name: 'Bob', age: 30, score: 80 }, { name: 'Eve', age: 25, score: 95 }, { name: 'Charlie', age: 28, score: 88 }, // New entry 1 { name: 'Grace', age: 28, score: 88 }, // New entry 2 ]; function App() { const [data, setData] = useState(initialData); const [sortKey, setSortKey] = useState(null); const handleSort = () => { const sortedData = [...data].sort((a, b) => a.age - b.age || b.score - a.score || a.name.localeCompare(b.name) ); setData(sortedData); setSortKey('ageScoreName'); }; return ( <div className='container'> <h1 className='title'>Sort an array of objects in ReactJS by multiple fields.</h1> <button className='sort-button' onClick={handleSort}>Sort by Age, Score, Name</button> <ul className='data-list'> {data.map((item, index) => ( <li className='data-item' key={index}> Name: {item.name}, Age: {item.age}, Score: {item.score} </li> ))} </ul> {sortKey && <p className='sort-info'>Sorted by: {sortKey}</p>} </div> ); } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> .container { padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); max-width: 600px; margin: 0 auto; } .title { font-size: 24px; margin-bottom: 20px; color: #333; } .sort-button { background-color: #007bff; color: #fff; border: none; border-radius: 5px; padding: 10px 20px; font-size: 16px; cursor: pointer; } .sort-button:hover { background-color: #0056b3; } .data-list { list-style: none; padding: 0; } .data-item { background-color: #fff; border: 1px solid #ddd; border-radius: 5px; padding: 10px; margin: 10px 0; } .sort-info { font-style: italic; color: #777; margin-top: 10px; } </style> </body> </html>