DEV Community

loading...
Cover image for Style your frontend with an engineering flavour by using JSS
Bornfight

Style your frontend with an engineering flavour by using JSS

ddrempe profile image Damir Drempetić Originally published at bornfight.com Updated on ・3 min read

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?

Discussion (7)

Collapse
khoa0319 profile image
Khoa Huỳnh

I would prefer my CSS to work when Javascript is disabled

Collapse
ddrempe profile image
Damir Drempetić Author • 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
Collapse
ronca85 profile image
ronca85

you won't fix css. you won't fix it by attempting to fix it on its own and you won't fix it by attempting to fix it as a part of a larger whole. it isn't broken. your approach makes sense to you and people like you, meaning the backend kind of people, the programmer, the engineer. i think it's horrible. all js frameworks make a mess of html, css and a11y and they fix very little if anything. all the old problems are still there.
one huge issue is the fact that you have welded your css into this project. therefor it isn't really reusable outside other react projects. keep it simple. css has to be a completely separate thing, in its own folder and framework agnostic. you just pop it into the project, import and use.

Collapse
ddrempe profile image
Damir Drempetić Author

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
saltarin profile image
saltarin

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

Collapse
koolkishan profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Kishan Sheth

Your Article was great.

Follow my YouTube Channel for amazing Web Development Tutorials.
youtube.com/channel/UCDT8sIFy3pW8L...

Forem Open with the Forem app