DEV Community

Cover image for Auto-Detect RTL in React with TypeScript! 🌐
ALI ALHARBI
ALI ALHARBI

Posted on

Auto-Detect RTL in React with TypeScript! 🌐

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;
Enter fullscreen mode Exit fullscreen mode

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)