Styled JSX for React: How and Why

栏目: IT技术 · 发布时间: 4年前

内容简介:“Styled-JSX is a very lightweight library (only 3kb) built and maintained by Next.JS. In the last couple of years, it has grown massively in popularity.As mentioned above, it does a very good job of making sure not to include unused CSS and encapsulate sty

Styled-JSX for React: How and Why

How and why you should use styled-jsx for your React SPA and SSR apps.

Jul 1 ·6min read

Styled JSX for React: How and Why

Styled JSX is a CSS-in-JS library that allows you to write encapsulated and scoped CSS to style your components. The styles you introduce for one component won’t affect other components, allowing you to add, change and delete styles without worrying about unintended side effects.” — Kristian Heruc

Styled-JSX is a very lightweight library (only 3kb) built and maintained by Next.JS. In the last couple of years, it has grown massively in popularity.

Styled JSX for React: How and Why

https://www.npmtrends.com/styled-jsx

As mentioned above, it does a very good job of making sure not to include unused CSS and encapsulate styling. Styled JSX also has source map support, and CSS preprocessing capabilities.

Styling in the Shared Components Era

Encapsulating styling has become an even greater concern in recent years as components are much more frequently shared and reused via tools and platforms like Bit ( Github ).

Unlike the “old days” when sharing components between apps meant building a complete ‘component library project’ — these days, sharing components is done continuously and from any project at all.

That means, what you build can easily be used in multiple other apps. You need to make sure everything is as modular and independent as possible. You also want to keep things clean without any unused CSS, following along a shared component.

Styled JSX for React: How and Why
Example: shared React components on Bit

Styled JSX vs other CSS-in-JS

If you’re not already familiar with that library, I suspect the first thing the comes to mind is: how is that different/better than other JS-in-CSS libraries?

Styled JSX is written in a more declarative way than you would usually see in other similar solutions. Writing declaratively is, after all, the “CSS way”. So, for those of us who prefer writing our styles as close as possible to plain CSS (without all the drawbacks of CSS), that could be a good solution.

In this article, we’ll look at the different benefits Styled JSX brings. We’ll try it out, both in a demo single-page app and server-side rendering app.

For example, this is a Button component that can receive the ‘padding’ prop to override the value set as default. The CSS part is plain and simple. The way to override is straightforward.

const Button = ({ padding, children }) => (
  <button style={{ padding }}>
     
  { children }
  
     <style jsx>{`
        button {
          padding: 20px;
          background: #eee;
          color: #999
        }
     `}</style>
  
  </button>
)

In contrast, a similar button will look like so, in styled-components:

const Button = styled.button`
    padding: ${props => props.padding || "20px"};
    background: #eee;
    color: #999
`

It’s more elegant but, again, may not be what you’re after. It’s less CSS-like.

Using Styled JSX

Styled JSX can use the styled-jsx-plugin-sass , styled-jsx-plugin-postcss , styled-jsx-plugin-less , or styled-jsx-plugin-stylus plugins to let us write code in SASS, LESS, Stylus, etc, and convert it to CSS when it’s built.

To generate source maps, we can add the sourceMaps property to true in .babelrc (to help with debugging).

For example

{
  "plugins": [
    ["styled-jsx/babel", { "sourceMaps": true }]
  ]
}

Use of Client-Side Rendered Apps (SPA)

We can use styled-jsx in our React app.

Install it by running:

npm install --save styled-jsx

Then in our .babelrc file, we add:

{
  "plugins": [
    "styled-jsx/babel"
  ]
}

Then in our React app, we can write, for example:

See it rendered: https://bit.dev/jauyeunggithub/styled-jsx-client-scoped

Notice how we didn’t have to import anything because we added the plugin to .babelrc .

style jsx transforms the CSS string we have into actual styles. It transpiles it to use to be used in the _JSXStyle component (which styled-jsx will import automatically during transportation).

For example, if we have:

export default () => (
  <div>
    <p>paragraph</p>
    <style jsx>{`
      p {
        color: green;
      }
    `}</style>
  </div>
)

Then it’ll be transpiled to:

import _JSXStyle from 'styled-jsx/style'export default () => (
  <div className="jsx-123">
    <p className="jsx-123">paragraph</p>
    <_JSXStyle id="123">{`p.jsx-123 {color: green;}`}</_JSXStyle>
  </div>
)

As mentioned earlier, _JSXStyle is the component that’s injected on render.

The styles are only injected once (even if a component is used more than once). The selectors of the CSS are matched with the elements one by one. That makes it easy to detect styles that haven’t been applied, during transpilation, and remove them.

We can use add the global prop to make the styles global.

For instance, we can write:

This will make the body’s background orange everywhere.

See it rendered: https://bit.dev/jauyeunggithub/styled-jsx-client-global

We can specify global styles to be applied for some selectors.

To do that, we write:

See it rendered: https://bit.dev/jauyeunggithub/styled-jsx-client-global/app

We used :global(.dropdown-placeholder) to apply the global style to only the div with the dropdown-placeholder class.

We can create dynamic styles with this library.

For instance, we can write:

This will create a button component with dynamic styles interpolated from prop values.

See it rendered: https://bit.dev/jauyeunggithub/styled-jsx-client-dynamic/app

We don’t have to specify the styles directly.

We can also specify styles for a given class name and set that as the value of the className property of the element to the given class name.

For instance, we can write:

import React from "react";const Button = props => (
  <button className={props.large && "large"}>
    {props.children}
    <style jsx>{`
      button {
        padding: 20px;
        background: orange;
        color: black;
      }
      .large {
        padding: 60px;
      }
    `}</style>
  </button>
);export default function App() {
  return (
    <div>
      <Button large>click me</Button>
    </div>
  );
}

We specify the class via the props. To make the padding large, we pass in the large prop to apply the large class. And, we specified that the large class has a padding of 60px.

We can also specify styles inline. For instance, we can write:

Server-Side Rendering

Styled-jsx works with server-side rendered apps.

Server-side rendering is always tricky if we do it from scratch.

The easiest way to create a server-side rendered app is to use ReactDOM Server with Express.

We also have to use @babel/register so that we can run modules.

To start, we install Babel, Express, React, and ReactDOM Server.

To do that, we create a project folder and install the packages by running:

npm i @babel/preset-env @babel/preset-react @babel/register @babel/core express ignore-styles react react-dom styled-jsx

In package.json , we add:

"scripts": {
  "start": "node --experimental-modules src/index.js"
},

This will enable loading ES modules.

Then we create a file called index.js and write:

require('ignore-styles')require('@babel/register')({
  ignore: [/(node_modules)/],
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: ["styled-jsx/babel"]
})require('./app')

We’ve to create this file because @babel/register 's transformations can only be applied to files outside the file that @babel/register is required in.

Then to create a simple server-side rendered app with ReactDOM server, React, Express, and styled-jsx, we write:

We’ve create the Hello component with styles generated from the getLinkStyles method. It takes an argument for the color of the p element text.

css.resolve defined scoped styles that resolve to the scoped className and styles element.

There’s also the css.global tag to define global styles.

We’ve to render both the styles and the classname to apply the styles.

Then in the GET route, which we created with app.get , we called ReactDOM.renderToString to render the Hello component to am HTML string.

We also called flushToHTML function from styled-jsx/server to return the styles in a string.

Then, we interpolate both into our HTML string, which we render with res.end on our server.

Then, we call app.listen(3000) to listen to requests on port 3000.

Now when we go to http://localhost:3000 , we should see Hello with red text.

The hard part is figuring our server-side rendering with React. Otherwise, styled-jsx can be used with server-side rendering without much trouble.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Elements of Statistical Learning

The Elements of Statistical Learning

Trevor Hastie、Robert Tibshirani、Jerome Friedman / Springer / 2009-10-1 / GBP 62.99

During the past decade there has been an explosion in computation and information technology. With it have come vast amounts of data in a variety of fields such as medicine, biology, finance, and mark......一起来看看 《The Elements of Statistical Learning》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具