Right to Left (RTL) React Support

What would be the best way to support RTL in React applications? Is there a way to override the default <p> and <span> tags (components) in order to add RTL support so I don't have to rewrite the components that I already wrote in order to have RTL support? (for example, to have some global window.RTL variable, so when set to true, so that all the <p> and <span> tags display the text direction in RTL). Maybe I can change the build system or create a babel plugin that replaces all React.createElement("p" ...) my own implementation of the p tag, but is there a better solution?

Thanks.

+5
source share
1 answer

A more optimal way is to use the CSS / HTML features for this:

  • direction CSS property
  • Unicode characters &rlm; / &lrm;
  • Attach .rtl / .ltr to body and use them to reorder

In this case, the order of your elements in HTML is the same for RTL and LTR. The difference in the applied CSS rules.

If you really need an element order in React, you can create your own component that changes the list of child elements if RTL:

 const Dir = React.createClass({ render: function() { let children = (this.props.direction == 'rtl' && this.props.children && this.props.children.reverse) ? this.props.children.reverse() : null; return <div> { children } </div>; } }); // And use as: // directionVariable = 'rtl'|'ltr' <Dir direction={ directionVariable }> <a>First</a> <a>Second</a> <a>Third</a> </Dir> 
+4
source

Source: https://habr.com/ru/post/1241017/


All Articles