Styling React with styled-jsx

Tram Ho

Styling React với styled-jsx

In projects using React, you must be very familiar with libraries to support writing styles like Styled-component, css-module. Thanks to such libraries, creating styling is easy, class name overlaps are no longer a concern. But have you ever heard of the styled-jsx library? This library allows you to write styles right in components, also known as single file components.

Styled-jsx

To install yourself, I need to add some small config

Now you are ready to code with style-jsx

Thanks to that, the library can help me avoid overlapping styles. Above, I can see that I am styling all the p tags, so what about the other unwanted p tags? That’s thanks to the babel plugin we just configured above for support on the identifiers for the tags we just want to target. The above code will be compile becomes

Paragraphs like jsx-123 are the identifiers that differentiate tags that need style. In case you want to write a global style, style-jsx also supports you

In many situations, you will need to override a library style, or simply style from a parent component to a child component, which is also very simple as follows:

With the attribute :global , the .react-select class in the Select component will be styled quickly. Only such classes can be styled.

The dynamic style case is as simple as when you transfer the prop

Conclusion

Above are some features that style jsx has supported that I have learned. This is a pretty cool library, well worth a day when you’ve become accustomed to old libraries. Hopefully you will be able to find interesting points when using this library like me.

References

https://github.com/zeit/styled-jsx

Share the news now

Source : Viblo