useDirection documentation
The `useDirection` hook manages text direction (LTR/RTL) state and provides a function to toggle between them. It can be used to dynamically change the text direction of an HTML element and persist the direction preference in local storage.
Type
import
import { useDirection } from '@pillar-ui/hooks'
Installation
No installation is needed beyond importing the hook directly into your React component:
import { useDirection } from '@pillar-ui/hooks'
Parameters
- element (optional): The optional HTML element to which the direction changes will be applied. If not provided, defaults to
document.documentElement
.
Returned Values
The useDirection
hook returns an object with the following properties:
isLtr
: A boolean indicating whether the current direction is Left-to-Right (LTR) (true
) or Right-to-Left (RTL) (false
).direction
: The current direction ('ltr'
or'rtl'
).directionScript
: A JSX element containing a script that can be injected into the document head.toggleDirection
: A function to toggle between LTR and RTL directions.
Usage
import { useDirection } from '@pillar-ui/hooks' // Adjust the path accordingly
function DirectionComponent() {
const { isLtr, toggleDirection, directionScript } = useDirection()
return (
<div>
<button onClick={toggleDirection}>Toggle Direction</button>
<p>Current direction: {isLtr ? 'LTR' : 'RTL'}</p>
{directionScript}
</div>
)
}
Implementation Details
The useDirection
hook initializes the direction based on the browser's default or the saved preference in local storage. It updates the direction state and applies it to the specified HTML element or document.documentElement
. The toggleDirection
function switches between LTR and RTL directions and updates both the UI and local storage accordingly.
TypeScript Support
The useDirection
hook is implemented in TypeScript, providing type definitions for its parameters and return values.
Example
You can use useDirection
to manage and toggle text direction dynamically within your React components, making it easy to support languages and layouts that require RTL support.