Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right to left (RTL) support in React

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

Thanks.

like image 654
Pavle Lekic Avatar asked Jan 20 '16 12:01

Pavle Lekic


People also ask

What is RTL in React?

React Data Grid: RTL - Right To Left. RTL is used for displaying languages that go from Right to Left, eg Hebrew and Arabic. To get AG Grid to display in RTL format, set the property enableRtl=true .

Does React support inheritance?

Inheritance allows the app to do the coupling between the parent-child component and reuse properties such as state values and function in its child components. React does not use inheritance except in the initial component class, which extends from the react package.


1 Answers

A more optimal way is to use CSS / HTML abilities for that:

  • direction CSS property
  • Unicode symbols &rlm; / &lrm;
  • Attach .rtl / .ltr classes to body and use them to change order

In that cases order of your elements in HTML are the same for RTL and LTR. The difference in applied CSS rules.

If you really need the order of elements in React, you can create own component that reverses the list of children 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>
like image 154
Dmitry Yaremenko Avatar answered Oct 27 '22 18:10

Dmitry Yaremenko