In React, to submit a form or trigger an action by pressing Enter, you can handle the onKeyDown
(or onKeyPress
) event on the input field. Here's a simple and clear way to implement it:
✅ Basic Example: Submit on Enter
<input
type="text"
value={apiParameters.promptText}
onChange={(e) =>
setApiParameters({ ...apiParameters, promptText: e.target.value })
}
onKeyDown={(e) => {
if (e.key === "Enter") {
onSubmitted(); // call your submit function
}
}}
placeholder="Type and hit Enter"
className="outline-none w-full py-4 px-2 bg-transparent text-white placeholder-zinc-400 text-lg"
/>
🧠 Notes:
e.key === "Enter"
ensures the function only triggers when Enter is pressed.- Works inside or outside a
<form>
. - If you're using a
<form>
, you can also handle submit directly:
<form onSubmit={(e) => { e.preventDefault(); onSubmitted(); }}>
<input ... />
</form>
Let me know if you want it styled or integrated with your current InputPrompt
component.