React
Concepts
Simple Textarea With Button
Displays a form textarea that captures user input and handle form submission.
// SimpleTextareaWithButton.tsx
import React, { forwardRef } from 'react';
const SimpleTextareaWithButton = forwardRef<HTMLTextAreaElement>(
({ className, onChange, onSubmit, ...props }, ref) => {
const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (event.key === "Enter" && !event.shiftKey) { // Detect Enter key without Shift
event.preventDefault(); // Prevent adding a new line
if (onSubmit) {
onSubmit();
}
}
};
return (
<>
<textarea
ref={ref}
onKeyDown={handleKeyDown}
onChange={onChange}
{...props}
/>
<button type="submit" onClick={onSubmit}>
Submit
</button>
</>
)
}
)
export {
SimpleTextareaWithButton
}
Usage
// App.tsx
import React, { useState, ChangeEvent } from 'react';
import { SimpleTextareaWithButton } from './SimpleTextareaWithButton.tsx'
export default function App() {
const [textareaValue, setTextareaValue] = useState(''); // State to track textarea value
const handleTextareaChange = (event: ChangeEvent<HTMLTextareaElement>) => {
const newValue = event.target.value;
setTextareaValue(newValue); // Update state with new textarea value
console.log('Current value:', newValue); // Show the current value
};
const handleSubmit = () => {
console.log('Submitted value:', textareaValue); // Show the value on submit
};
return (
<>
<h1>Simple Textarea With Button Example</h1>
<SimpleTextareaWithButton onChange={handleTextareaChange} onSubmit={handleSubmit} />
</>
)
}
Example Output
Current value: H
Current value: Hi
Submitted value: Hi
Last updated