React styling. Plain and simple.

Related tags

CSS classy
Overview

Classy logo

npm version npm downloads build status dependency status devdependency status


Table of Contents

Install

npm install react-classy

Getting Started

Classy makes styling React components composable, extensible, and simple. Implementation requires only 3 steps:

  1. Import react-classy into your React component module
  2. Decorate your React component class with @Classy.
  3. Assign a CSS string to a static style prop on your React component class.

The styles defined on your React component will get automatically injected into the DOM right before your component mounts. Check out some examples of basic and advanced usage in the next section.

Usage

Basic

import React, { Component } from 'react';
// Import Classy
import Classy from 'react-classy';

// Decorate your component
@Classy
export default class Button extends Component {
  // Add your CSS styles
  static style = `
    .button {
      background: blue;
    }
  `
  render() {
    return (
      <button className="button">
        {this.props.children}
      </button>
    );
  }
}

Advanced

Classy is also highly customizable and supports asynchronous style rendering, custom middleware, and theming! In the next example, we'll demonstrate all of the aforementioned while creating a button that switches themes when clicked.

import React, { Component } from 'react';
// Import the decorator and utils modules
import Classy, { Utils } from 'react-classy';
// CSS pre-processor
import stylus from 'stylus';

@Classy({

  // Makes Classy play nice with react-hot-loader :)
  hot: true,

  // Logs component css to console
  debug: true,

  // Will access specified prop to load component styles
  // instead of default `style` prop
  styleProp: 'stylus'

})
export default class ToggleButton extends Component {

  render() {
    return <button {...this.props} />;
  }

  static defaultProps = {
    className: 'toggle-button toggle-button--default',
    children: 'Touch Me!',

    // Method that switches the component's theme.
    // Will toggle from 'light' to 'dark' and vice versa.
    onClick: function switchTheme(e) {
      let { name } = ToggleButton;
      let theme = Utils.getTheme(name);
      theme = 'dark' === theme ? 'light' : 'dark';
      Utils.setTheme(name, theme);
    }

  }

  // Let's define our themes as a static.
  // This makes it easy for others to modify a component's theme(s)
  // via class extension.
  static theme = {
    light: {
      textColor: '#a24bcf',
      background: 'transparent',
      borderRadius: '30px'
    },
    dark: {
      textColor: '#fff',
      background: '#4b79cf',
      borderRadius: '4px'
    }
  }

  // Instead of a hard-coding your CSS,
  // you can assign a method that returns Promise that fulfills a CSS string.
  // Our default theme is set via rest param.
  static stylus(theme=ToggleButton.theme.light) {
    let styl = `

    .toggle-button

      &--default
        color: convert($theme.textColor)
        background: convert($theme.background)
        border: 1px solid convert($theme.textColor)
        border-radius: convert($theme.borderRadius)
        outline: none
        padding: 20px
        font-size: 18px
        font-family: 'Helvetica Neue', helvetica, sans-serif
        transition: transform .3s ease

        &:hover
          cursor: pointer

        &:focus
          transform: translateY(4px)

    `;
    // Finally, let's use our Stylus middleware to render actual CSS
    // and return it with a Promise
    return new Promise((yep, nope) => stylus(styl.trim())
      .define('$theme', theme, true)
      .render((err, css) => err ? nope(err) : yep(css))
    );
  }

}

Decorator options and utility methods are comprehensively documented in the next section.

API

Decorator

@Classy([options])

A class decorator will automatically inject styles into the DOM before your ReactComponent instance mounts.

Example:

// ES2016
@Classy
export default class MyComponent extends React.Component { ... }

// ES2015
class MyComponent extends React.Component { ... }
export default Classy(MyComponent);

// ES5
var MyComponent = React.createClass({ ... });
module.exports = Classy(MyComponent);
options

Type: Object

Default: see below

An object that allows you to customize your Classy component settings. All settings are optional. See defaults below.

options.debug

Type: Boolean

Default: false

Logs rendered cssText to debug console whens component styles are updated

options.hot

Type: Boolean

Default: false

Applies two effects:

  • Replaces internal ref to the component if it gets hot-loaded
  • Component never uses cached cssText
options.styleProp

Type: String

Default: style

Component prop to access for getting styles

options.themeProp

Type: String

Default: themes

Component prop to access for getting themes

options.alias

Type: String

Default: <ReactComponent>.name

Key under which Classy identifies your component. If not specified, your ReactComponent's constructor.name will be used.

options.elemId

Type: String

Default: alias + '_' + Utils.genHash()

Example: MyButton_fxhhf

ID prop for component <style> tag. Uses options.alias plus a 5 character hash (separated by an underscore) to prevent unintentional id attribute collisions.

options.elemProps

Type: String

Default: { type: 'text/css' }

Other props to apply to component <style> tag

options.appendTo

Type: String

Default: head

Element to append component <style> tag to


Utils

#setTheme(alias [, theme, force=false])

Updates component styles with specified theme object

alias

Type: String

Key under which Classy identifies your component. (See decorator options)

theme

Type: String

Component theme to use

force

Type: Boolean

Default: false

Re-render theme if already applied

#getTheme(alias)

Return: Object

Gets the current theme applied to a component (Convenience method for State.getComponentState(...).currentTheme).

alias

Type: String

Key under which Classy identifies your component. (See decorator options)

#updateStyle(alias)

Return: Promise

Creates a component's <style> tag and/or updates its cssText.

alias

Type: String

Key under which Classy identifies your component. (See decorator options)

#removeStyle(alias)

Return: Promise

Removes a component's <style> tag.

alias

Type: String

Key under which Classy identifies your component. (See decorator options)

#getComponentState(alias)

Return: Object

Gets a component's Classy state object.

alias

Type: String

Key under which Classy identifies your component. (See decorator options)

You might also like...

Minimal Portfolio Page Built with React

Minimal Portfolio Page Built with React

Minimal Portfolio Page Built with React Documentation : https://github.com/singhkshitij/My-Landing-Page/wiki/ Demo https://singhkshitij.github.io/My-L

Dec 19, 2022

Small utility for react-redux's `useSelector` that allows passing args.

use-selector-with Monorepo for the following two packages: use-selector-with: Small utility for react-redux's useSelector that allows passing args. es

Jan 28, 2022

rede social inspirada no youTube para aprendizado na area da programação utilizando o react js juntamente com typescript

media for devs a rede social de videos para programadores link do projeto api repositorio projeto feito com o objetivo de exercitar minhas skills tant

Nov 26, 2021

Set of react components based on styled-components

React to styled Links Documentation Contributing Ask question or give feedback Packages @react-to-styled/components – all components in one package @r

Jan 1, 2023

AngularJS SPA Template for Visual Studio is a project skeleton for a simple single-page web application (SPA) built with AngularJS, Bootstrap, and ASP.NET (MVC, Web Api, SignalR).

AngularJS SPA Template for Visual Studio is a project skeleton for a simple single-page web application (SPA) built with AngularJS, Bootstrap, and ASP.NET (MVC, Web Api, SignalR).

AngularJS SPA Template for Visual Studio This project is a skeleton for a simple single-page web application (SPA) built on top of the: AngularJS 1.2.

Jun 18, 2022

A Simple and beautiful template for blog or portfolio using Next js.

Next js Blog Configuration Update your name in theme.config.js or change the footer. Update your name and site URL for the RSS feed in scripts/gen-rss

Apr 20, 2022

The fastest way to build beautiful Electron apps using simple HTML and CSS

Photon UI toolkit for building desktop apps with Electron. Getting started Clone the repo with git clone https://github.com/connors/photon.git Read th

Dec 29, 2022

Math magicians is a single page app for all mathematics lovers. Math Magicians allow users to perform simple calculations and It generates mathematics quotes.

Math magicians is a single page app for all mathematics lovers. Math Magicians allow users to perform simple calculations and It generates mathematics quotes.

Math Magicians Math Magician is a single Page App that have three interfaces. It allows users to perform simple math calculations, user can read the m

Aug 21, 2022

Skeleton: A Dead Simple, Responsive Boilerplate for Mobile-Friendly Development

Skeleton Skeleton is a simple, responsive boilerplate to kickstart any responsive project. Check out http://getskeleton.com for documentation and deta

Dec 29, 2022
Owner
Inturn
Inturn is the first marketplace that helps fashion and lifestyle brands efficiently sell their excess inventory to retailers.
Inturn
RxHtmlButtonLibrary - Html Button Styling Library by roxunlimited.com using CSS and jQuery.

rxHTMLButton Library v0.3 rxHTMLButton Library will work on almost every HTML tag. It will smoothly work on 'a href link', 'button type button', 'inpu

roxunlimited 0 Sep 16, 2022
Deploying a React App (created using create-react-app) to GitHub Pages

Deploying a React App* to GitHub Pages * created using create-react-app Introduction In this tutorial, I'll show you how I deployed a React app—which

gitname 4.4k Dec 31, 2022
A package of small but beautiful React components from the planet, Pluto. 🔵 Get minimal components for your React based applications 😍

React Pluto Component Design System + UI Kit A package of small but beautiful React components from the planet Pluto. To install the latest version, r

Yash Sehgal 17 Aug 8, 2022
Fluent UI web represents a collection of utilities, React components, and web components for building web applications.

Fluent UI Web ?? ?? ?? Version 8 of @fluentui/react is now available on npm! ?? ?? ?? See the release notes for more info, and please file an issue if

Microsoft 14.5k Jan 4, 2023
styled component for react & style-loader/usable

react-styled ES7 decorator for dynamic stylesheet usage w/ webpack install $ npm install bloody-react-styled --save-dev require import styled from "bl

Matthias Le Brun 37 Sep 26, 2022
Use CSS-in-JavaScript with themes for React without being tightly coupled to one implementation

react-with-styles Use CSS-in-JavaScript for your React components without being tightly coupled to one implementation (e.g. Aphrodite, Radium, or Reac

Airbnb 1.7k Dec 8, 2022
A React.js Nice Resume Template

React Nice Resume DEMO is here About particles-bg library This project uses the react particle background component library https://github.com/lindelo

Nordic Giant 476 Dec 28, 2022
A react wonderful landingpage template

Wonderful Landing Page Template LIVE DEMO Description This is a ReactJS based landing page template, fit for a startup company/service with a one page

wonderful landing page 104 Jan 6, 2023
Startup Landing Page Components for React.js

neal-react neal-react is a collection of reactjs components to quickly build landing pages. I found that using hosted services like Launchrock doesn't

Denny Britz 1.4k Nov 30, 2022