Enter Key Shortcut
ReactJS
Hard
6 views
Problem Description
Handle Enter key press to submit a message using document keydown.
Output Format
Render a React component.
Constraints
Add keydown listener and clean it up.
Official Solution
import React, { useEffect, useState } from 'react';
export default function App() {
const [text, setText] = useState('');
const [sent, setSent] = useState([]);
function send() {
const t = text.trim();
if (!t) return;
setSent((prev) => [{ id: Date.now(), text: t }, ...prev]);
setText('');
}
useEffect(() => {
function onKeyDown(e) {
if (e.key === 'Enter') {
e.preventDefault();
send();
}
}
document.addEventListener('keydown', onKeyDown);
return () => document.removeEventListener('keydown', onKeyDown);
});
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode quick message</h2>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder='Type and press Enter' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<ul style={{ marginTop: 12, paddingLeft: 18 }}>
{sent.map((m) => <li key={m.id}>{m.text}</li>)}
</ul>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!