Skip to content
2k
On This Page

Direction

A provider component that sets the text direction for your application.

The DirectionProvider component is used to set the text direction (ltr or rtl) for your application. This is essential for supporting right-to-left languages like Arabic, Hebrew, and Persian.

Here’s a preview of the component in RTL mode. Use the language selector to switch the language. To see more examples, look for the RTL section on components pages.

Installation

pnpm dlx solidui-cli@latest add direction

Copy and paste the following code into your project.

components/ui/direction.tsx
import type { JSX } from "@solidjs/web"
import { createContext, useContext, type Accessor } from "solid-js"

type Direction = "ltr" | "rtl"
type DirectionProviderProps = {
  children: JSX.Element
  direction?: Direction
  locale?: string
  class?: string
}
const DirectionContext = createContext<Accessor<Direction>>(() => "ltr")
const DirectionProvider = (props: DirectionProviderProps) => {
  const direction = () =>
    props.direction ??
    (props.locale && /^(ar|fa|he|ur)(-|$)/i.test(props.locale) ? "rtl" : "ltr")
  return (
    <DirectionContext value={direction}>
      <div dir={direction()} lang={props.locale} class={props.class}>
        {props.children}
      </div>
    </DirectionContext>
  )
}
const useDirection = (): Accessor<Direction> => useContext(DirectionContext)
export {
  DirectionProvider,
  useDirection,
  type Direction,
  type DirectionProviderProps
}

Update the import paths to match your project setup.

Usage

import { DirectionProvider } from "~/components/ui/direction"
<html lang="ar" dir="rtl">
  <body>
    <DirectionProvider direction="rtl">
      <main>محتوى التطبيق</main>
    </DirectionProvider>
  </body>
</html>

useDirection

Use useDirection() to read the current direction from context.

import { useDirection } from "~/components/ui/direction"
 
const Example = () => {
  const direction = useDirection()
 
  return <div>Current direction: {direction()}</div>
}