Right-to-left support
Learn how to implement right-to-left (RTL) text with Joy UI to support languages such as Arabic, Persian, and Hebrew.
Setup
This guide outlines the three steps necessary to change the direction of text-based components in Joy UI to support RTL languages, as shown in the demo below:
1. Set the HTML direction
You can set the text direction either globally (across the entire app) or locally (specific to individual components), depending on your use case.
Globally
Add dir="rtl"
to the app's root <html>
tag to set the global text direction:
<html dir="rtl"></html>
If your React app doesn't control the root <html>
, use the JavaScript API before the component tree is rendered, as a workaround:
document.dir = 'rtl';
Locally
Add the dir="rtl"
attribute to any other HTML element or React component if you need limit the scope of the text direction to that element and its children.
2. Set the theme direction
Use the extendTheme
API to set the theme direction to 'rtl'
:
import { extendTheme } from '@mui/joy/styles';
const theme = extendTheme({
direction: 'rtl',
});
3. Configure RTL style plugin
Install the stylis-plugin-rtl
using one of the commands below:
npm install stylis stylis-plugin-rtl
With Emotion
If you're using Emotion, use the CacheProvider to create a new cache instance that uses rtlPlugin
from stylis-plugin-rtl
and add that to the top of your application tree:
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { prefixer } from 'stylis';
import rtlPlugin from 'stylis-plugin-rtl';
// Create rtl cache
const cacheRtl = createCache({
key: 'muirtl',
stylisPlugins: [prefixer, rtlPlugin],
});
function Rtl(props) {
return <CacheProvider value={cacheRtl}>{props.children}</CacheProvider>;
}
With styled-components
If you're using styled-components, use the StyleSheetManager and provide rtlPlugin
to the stylisPlugins
property:
import { StyleSheetManager } from 'styled-components';
import rtlPlugin from 'stylis-plugin-rtl';
function Rtl(props) {
return (
<StyleSheetManager stylisPlugins={[rtlPlugin]}>
{props.children}
</StyleSheetManager>
);
}
Opting out of RTL locally
To turn off RTL on specific components, use the template literal syntax and add the /* @noflip */
directive:
const LeftToRightTextInRtlApp = styled('div')`
/* @noflip */
text-align: left;
`;