Use CSS in React-Native with rn-css

Limitations of styled-components for native

styled-components library comes with styled-components/native to handle the development of components in React Native. This sub-library presents a major drawback: the range of supported css is very limited. Here is a list of the lacking features

  • Units (em, rem, pt, pc, %, …)
  • Media-queries
  • Hover effects
  • Transitions
  • Animations
  • text-overflow
  • overflow (scroll)
  • z-index

Presentation of rn-css

rn-css works perfectly fine in React-Native and React-Native-Web projects. You can use it easily in existing projects by replacing all occurrences of styled-components/native by rn-css within your code.

  • Units (em, rem, pt, pc, %, …)
  • Media-queries
  • Hover effects
  • text-overflow
  • unified z-index behavior
  • min, max and calc support within your css
  • Inject CSS style as a CSS string
  • Convert any CSS string into React-Native style
  • Access the em current value to programmatically convert pixels into em

CSS units

This is the main feature. Check out how you can create a circle that will adapt to the font size of the text without any calculation on your side.

Hover

Using &:hover, you can add some style that will be applied only on hover. This relies on onMouseEnter/ onMouseLeave props and will be available only for web.

Ellipsis

For responsive design, you probably want your text to shrink and use ellipsis when too long?

ellipsis example

Inline css injection

This is my favorite feature. Did you ever find annoying to create a new styled-component just to add a margin or some small style details? You don’t need that anymore. Just inject the style as an inline prop:

Access current em value

This feature might not look like it, but it can be very handy. You can access the current value of em to manually convert pixels into em.

Convert CSS into RN style

Finally, you might wonder how you can use CSS with components or libraries that do not rely on rn-css? Well, you can simply convert your css into React-Native style object with the function cssToRNStyle .

Conclusion

I hope this article will help you improve your dev experience with cross-plateform apps in React-Native. I didn’t mention some other features of rn-css that you can check out in the Readme. There are also some new features still in development to add yet another range of css to React Native (overflow, transitions, animations…).

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store