Search code examples
javascriptreactjsmaterial-uiright-to-left

RTL on TextInput works on every other render


I have a weird issue with RTL where seemingly everything is flipped properly except for TextInput's - which work ~50% of the time. Here is a gif showing the issue as I toggle the language between English and Hebrew:

(click for larger image)

Here is the Theme component I have my tree wrapped in.

import React, {useContext} from 'react'
import {create} from 'jss'
import jssRtl from 'jss-rtl'
import JssProvider from 'react-jss/lib/JssProvider'
import {
  createGenerateClassName,
  jssPreset,
  MuiThemeProvider,
  createMuiTheme
} from '@material-ui/core/styles'
import CssBaseline from '@material-ui/core/CssBaseline'
import {UserContext} from 'src/context/user.js'

const generateClassName = createGenerateClassName()
const plugins = [...jssPreset().plugins]
const dir = locale => {
  const base = locale.split('-') || []
  return ['he', 'ar'].includes(base[0]) ? 'rtl' : 'ltr'
}

const setDir = dir => {
  window.document &&
    window.document.getElementsByTagName('body')[0].setAttribute('dir', dir)
}

export default function Theme({children}) {
  const {locale} = useContext(UserContext)
  const direction = dir(locale)
  const theme = createMuiTheme({direction, useNextVariants: true})
  if (direction === 'rtl') plugins.push(jssRtl())
  setDir(direction)
  console.log('theme', {locale, direction})

  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      {direction === 'rtl' ? (
        <JssProvider
          jss={create({plugins})}
          generateClassName={generateClassName}
        >
          {children}
        </JssProvider>
      ) : (
        children
      )}
    </MuiThemeProvider>
  )
}

Solution

  • Wild guess: Try adding the jssRtl pugin once. You are adding the jssRtl plugin on every render of the Theme component. That might explain that it won't work 50% of the time since every even render means flipping twice which equivalent to not flipping.