I have made a decision to try StyleX in a new React project. I usualy build styles with style-components but I find the simplicity of StyleX to be very attractive.
I have gone through StyleX short documentation and the Thinking in StyleX
section a few times. However, I am stuck at two fundamental points:
-
In a multi-language website, how I go about defining different styles like
direction
andfontFamily
for different languages. Is this a matter of Theme, or is it more about defining styles dynamically? Should I create a theme for language and another theme for colors and other design elements and apply both themes as explained here? -
When building a components library with StyleX, should every component expect to receive "custom style(s)" and a "theme" as props?
2
Answers
Here is how I implemented the required language feature:
I created a
Root
component which acceptslang
andchildren
as props:In the
App
component, I used the component and passed the current value oflang
to it.CSS supports LTR and RTL languages using logical style properties. StyleX supports them. TLDR; Don’t use any styles with the words “left” or “right” in them. For example, use
marginInlineStart
andmarginInlineEnd
. This will make your styles work correctly for all languages without needing separate styles.Next,
direction
is actually a CSS property, so you can applydirection: ‘ltr’
ordirection: ‘rtl’
based on the language that is current active on the page. Of course, you should also set thelang
attribute.If you can’t apply styles on your
html
tag directly, using an effect as explained by @damascus is a valid solution.If you’re trying to change themes per languages, applying multiple themes is the correct solution too.
This depends on how strict your designs are. If a component can be customized, it should accept styles. It’s probably not useful to accept a
theme
prop in most cases though, because themes are inherited anyway and can be applied on a container element.A theme prop only makes sense on large “container” components where you may reasonably want to change the active theme.
Overall, your instincts are correct. Feel free to create a discussion post on the StyleX repo with further questions.