DEV Community

Cover image for Candy - new way of styling react components
Dani Chu
Dani Chu

Posted on

Candy - new way of styling react components

Hello! My name is Dan.

I developed a new approach to styling react components. In this article, I want to tell you about it.

The idea is very simple. We write the usual css, sass, less.

/* styles.css */

.root {
    color: white;
}

.red {
    backgroung-color: red;
}
Enter fullscreen mode Exit fullscreen mode

And then we import html-tags-components from the style file. Each such component tag has boolean properties associated with the names of css classes.

import { Div } from './styles.css'

function Component(props) {
    return (
        <Div root red={props.red}>
            ...
        </Div>
    )
}
Enter fullscreen mode Exit fullscreen mode

This opportunity is provided by a special webpack-loader - candy-loader.

We get the opportunity to write the usual css and the same familiar html. You can import any standard html tag. Tags are capitalized and extended with an additional set of properties, from which the className property is generated under the hood.

You can include css files and access their styles.

/* styles.css */
@import 'grid.css';

/*...*/
Enter fullscreen mode Exit fullscreen mode
import { Div } from './styles.css'

function Component(props) {
    return (
        <Div root red={props.red} col_xs_12 col_sm_8>
            ...
        </Div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Easy configurable

candy-loader is based on postcss, so you can use the standard config file for further customization.

// .postcssrc.js

module.exports = {
    plugins: {
        autoprefixer: isProduction,
    },
    processOptions: {
        map: isDevelopment,
    },
}
Enter fullscreen mode Exit fullscreen mode

Intellisense

There is a typescript-plugin-candy for that. A fairly easy to install and configure plugin that allows you to get autocomplete and type checking.

Intellisense

Conclusion

What do you think about this idea? Should it be further developed and improved?

Below I have provided links to the source code and a pre-made starter repo in case you want to play around with it.

I will be glad to your comments and suggestions for development.

Thanks!

Top comments (0)