Official Solution
import React, { useState } from 'react';
export default function App() {
const [items, setItems] = useState(['HTML', 'CSS', 'React', 'PHP']);
function swap(i, j) {
setItems((prev) => {
const next = [...prev];
const tmp = next[i];
next[i] = next[j];
next[j] = tmp;
return next;
});
}
return (
<div style={{ padding: 16, width: 420 }}>
<h2 style={{ marginTop: 0 }}>meetcode order</h2>
<ol style={{ paddingLeft: 18 }}>
{items.map((name, idx) => (
<li key={name} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '6px 0' }}>
<span>{name}</span>
<span style={{ display: 'inline-flex', gap: 8 }}>
<button type='button' disabled={idx === 0} onClick={() => swap(idx, idx - 1)} style={{ padding: '6px 10px', borderRadius: 12, border: '1px solid #ddd', background: '#fff', opacity: idx === 0 ? 0.6 : 1 }}>Up</button>
<button type='button' disabled={idx === items.length - 1} onClick={() => swap(idx, idx + 1)} style={{ padding: '6px 10px', borderRadius: 12, border: '1px solid #ddd', background: '#fff', opacity: idx === items.length - 1 ? 0.6 : 1 }}>Down</button>
</span>
</li>
))}
</ol>
</div>
);
}
No comments yet. Start the discussion!