Ever wanted your text input to automagically switch direction based on what users type? Letβs build a React component that detects Right-to-Left (RTL) languages like Arabic in real timeβwith just a few lines of TypeScript! No libraries, no hassle.
The Magic Code πͺ
Hereβs all you need for instant direction switching based on input:
import { ChangeEvent, useState } from 'react';
const App = () => {
const [direction, setDirection] = useState<'ltr' | 'rtl'>('ltr');
const handleInputChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
const text = event.target.value;
const rtlRegex = /[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F]/;
setDirection(rtlRegex.test(text) ? 'rtl' : 'ltr');
};
return (
<textarea
dir={direction}
placeholder="Type something..."
onChange={handleInputChange}
/>
);
};
export default App;
How It Works π
-
State Magic: useState sets the direction to either
'ltr'
or'rtl'
. - RTL Detection: We use a simple regex to detect Arabic script. If it finds RTL characters, the direction flips to rtl; otherwise, it stays ltr.
-
Dynamic Direction: The
dir={direction}
attribute on<textarea>
updates as you type, giving an instant RTL effect.
Why This Rocks π
Lightweight: No extra libraries needed.
Instant Feedback: Typing adjusts direction as you go.
Type Safety: TypeScript keeps direction locked to 'ltr'
or 'rtl'
only.
Give it a try! Your input fields will never be the same. ππ
Top comments (0)