DEV Community

Cover image for Style your frontend with an engineering flavour by using JSS
Damir Drempetić for Bornfight

Posted on • Edited on • Originally published at bornfight.com

Style your frontend with an engineering flavour by using JSS

Choosing between numerous options for styling your app could be a project in and of itself. 🤯

I've tried several styling solutions and approaches on frontend like:

Projects which used them were written either with Vanilla JS or with some modern JavaScript frameworks like AngularJS, Angular 4, React ⚛️ or even React Native.

After all I have a huge favourite regarding styling options world which is not mentioned above. I would vote for it on new project anytime (sorry, there are local elections 🗳️ soon here in Croatia).

To finally get closer to the point, I like to write my styles just as rest of the app. In JavaScript. Which means I use the same programming language and the same syntax both for logic and for styles. This is really cool, but it's not the main motive behind it. It's because I find JavaScript much more powerful 💪 and capable than CSS.

JavaScript brings more of the engineering flavour into the app styling process. And it's possible with CSS-in-JS solutions, or shorter JSS.

I used JSS for the first time while I was working on projects built with Material UI. In their docs, you can find out why they use such approach after abandoning Less and custom solution inline-styles. Actually they did some pretty interesting comparison 📊 when choosing styling solution.

I've mentioned engineering flavour so let's show some examples of what I thought.

Variables

You can simply keep any style in a variable.

const COLOR_PRIMARY = "black";
const COLOR_SECONDARY = "#f0f0f0";
Enter fullscreen mode Exit fullscreen mode

Also group them into a JS object.

baseTitle: {
    fontSize: 24,
    fontWeight: 600,
    color: COLOR_PRIMARY
}
Enter fullscreen mode Exit fullscreen mode

You could think now: nothing special, I can do that with extended CSS too. Be patient... 😃

Spreading, default properties and overriding

Let's say we want to extend this basic title for some other use.

sectionTitle:  {
  ...baseTitle,
  //override font weight from base title
  fontWeight: 800, 
  //extend base title
  fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
  fontStyle: 'italic',
}
Enter fullscreen mode Exit fullscreen mode

Notice that you don't need to learn any new syntax, you actually write CSS but you just use camelCase instead of the kebab-case: font-size ➡️ fontSize. And have JS power on top of it.

Themes

Then, you could also keep all your reusable styles in one place and build your whole theme - which is simply JS object.

const theme = {
  backgroundColor: COLOR_PRIMARY,
  color: COLOR_SECONDARY,
  ...
};
Enter fullscreen mode Exit fullscreen mode

That theme could be considered a config file but for styles 💅. Use Material UI theme for inspiration. From breakpoints, typography to colour palette and spacings.

Integrate JSS with React

There is a JSS Core library which can be used in any Javascript app, but React developers will be more interested in React-JSS.

Dynamic Values

Give attention to Dynamic values .

JSS uses Hooks API where you can use hooks like createUseStyles.

There is a cool example I will borrow from JSS docs about how to start with it. I will just separate a style from components, because it is always a good practice not to make a big clutter in one file. Also, it reminds of the CSS modules approach which have a separate isolated style for each component.

useButtonStyles.js

import { createUseStyles } from 'react-jss'

export const useButtonStyles = createUseStyles({
  myButton: {
    padding: props => props.spacing
  },
  myLabel: props => ({
    display: 'block',
    color: props.labelColor,
    fontWeight: props.fontWeight,
    fontStyle: props.fontStyle
  })
})
Enter fullscreen mode Exit fullscreen mode

Notice how elegantly you can change the style depending on props values passed from the component.

index.js

import React from 'react'
import { useButtonStyles } from "./useButtonStyles";

const Button = ({children, ...props}) => {
  const classes = useButtonStyles(props)
  return (
    <button className={classes.myButton}>
      <span className={classes.myLabel}>{children}</span>
    </button>
  )
}

Button.defaultProps = {
  spacing: 10,
  fontWeight: 'bold',
  labelColor: 'red'
}

const App = () => <Button fontStyle="italic">Submit</Button>
Enter fullscreen mode Exit fullscreen mode

Feel free to play with example on CodeSandbox.

Theming

Besides hook for creating style there is the useTheme combined with a ThemeProvider wrapper. It also provides a theming solution which makes it a lot easier to start writing themed apps with reusable styles, and to quick start your new project.

Would you give it a try?

❓ What are you thoughts?
❓ Which styling solution do you prefer?
❓ How do you deal with theming and reusable styles?

Top comments (8)

Collapse
 
khoahuynhdev profile image
Khoa Huỳnh

I would prefer my CSS to work when Javascript is disabled

Collapse
 
ddrempe profile image
Damir Drempetić • Edited

@khoa0319 JSS compiles to CSS so no worries about that :)

It can compile in the browser, server-side or at build time in Node.

There are examples like this demonstrating it: cssinjs.org/react-jss?v=v10.6.0#basic

Collapse
 
peb7268 profile image
Paul Barrick

😂

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
ddrempe profile image
Damir Drempetić

Hi @ronca85 , thank you for your comment!

Each tool has its usage and cases where it is great and helpful and on the opposite side where it is overkill or some kind of burden instead. JSS is not an exception. :)

For some smaller sites and projects there wouldn't be a lot of benefits of using JSS and maybe even React, so of course it can be built with good old CSS.

But if you are building some bigger enterprise application, or if you need to build some kind of design system or component library which can be reused across projects and apps, I like it how React with JSS solves this requirement for me. Because I can organise styles systematically, keep them consistent and manageable at one place (in theme).

I never had a need for reusing just a style (implemented in css, jss or any other technology), but always some piece of UI, or to be more precise some component. So I find it natural that style is tied to some html element or more complex React component.

Keep in mind this is my experience cause I'm oriented on products and applications where a lot of attention should be given also how app is built and how maintainable it is. If I would be building sites or some presentational web elements, I would have some different mindset.

Do you have some examples of reusing css across projects? How do you keep styles framework agnostic and just import and use them. It's always cool to see other approaches! :) Cheers!

Collapse
 
kr4idle profile image
Pete Steven • Edited

CSS in JS. Another way to merge domains that should be kept separate. I think if people would learn html, css and js, instead of tailwind, bootstrap and react, then people would understand the core web technology better and use it as it is expected to work.

You can also use Desech Studio to visually create clean html structure positioned with css grids, to speed up your development process. But you can also integrate it with your js flavor of react, angular, vue.

Collapse
 
saltarin profile image
saltarin

I like it hook but its the same that styled-components or emotion.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.