Skip to content

Latest commit

 

History

History
337 lines (232 loc) · 7.61 KB

js-api.md

File metadata and controls

337 lines (232 loc) · 7.61 KB

JavaScript API

Access the global JSS instance

import jss from 'jss'

Create an own JSS instance

create([options])

Use an own instance if the component you build should be reusable within a different project with a probably different JSS setup.

See .setupfor options description.

import {create} from 'jss'
const jss = create()
jss.use(somePlugin())
jss.createStyleSheet(...)
export default jss

Setup JSS instance

jss.setup(options)

Options:

  • generateClassName function you can pass to generate your custom class name.
  • plugins an array of functions, will be passed to jss.use.
  • insertionPoint the value of a DOM comment node which marks the start of sheets. Sheets rendered by this Jss instance are inserted after this point sequentially. Default is jss.

Quick setup with preset

import preset from 'jss-preset-default'
import jss from 'jss'

jss.setup(preset())

Create Style Sheet

jss.createStyleSheet([styles], [options])

Classes are always generated by default.

Options:

  • media media query - attribute of style element.
  • meta meta information about this style - attribute of style element, for e.g. you could pass component name for easier debugging.
  • link link jss Rule instances with DOM CSSRule instances so that styles, can be modified dynamically, false by default because it has some performance cost.
  • element style element, will create one by default
  • index 0 by default - determines DOM rendering order, higher number = higher specificity (inserted after)
  • virtual if true, use VirtualRenderer
  • insertionPoint the value of a DOM comment node which marks the start of sheets. Sheets rendered by this Jss instance are inserted after this point sequentially. Default is jss.
const sheet = jss.createStyleSheet({
  // "button" is a rule name, class is generated.
  button: {
    width: 100,
    height: 100
  }
}, {media: 'print'}).attach()

console.log(sheet.classes.button) // button-d4f43g
<style media="print">
  .button-d4f43g {
    width: 100px;
    height: 100px;
  }
</style>

Create a Style Sheet with global selectors

You need to have jss-global plugin installed.

Style Sheets registry

SheetsRegistry

When rendering on the server, you will need to get all rendered styles as a CSS string. SheetsRegistry classs allows you to manually aggregate and stringify them. Read more about SSR here.

import jss, {SheetsRegistry} from jss

const sheets = new SheetsRegistry()
const sheet = jss.createStyleSheet()
sheets.add(sheet)
sheets.toString() // Returns CSS of all attached Style Sheets together.

Remove a Style Sheet

jss.removeStyleSheet(sheet)

Detach the Style Sheet and remove it from the registry.

Attach Style Sheet

sheet.attach()

Insert Style Sheet into the render tree. You need to call it in order to make your Style Sheet visible for the layout.

Detach Style Sheet

sheet.detach()

Detaching unused Style Sheets will speedup every DOM node insertion and manipulation as the browser will have to do less lookups for css rules potentially to be applied to the element.

Attach Style Sheets in a specific order

Sheet 1 has a higher index (priority), and as such will come after sheet 2 in the resulting DOM.

const sheet1 = jss.createStyleSheet({}, {index: 5, meta: 'sheet-1'}).attach()
const sheet2 = jss.createStyleSheet({}, {index: 1, meta: 'sheet-2'}).attach()
<style type="text/css" data-meta="sheet-2"></style>
<style type="text/css" data-meta="sheet-1"></style>

Add a rule to an existing Style Sheet

sheet.addRule([name], style, [options])

Options

  • index index where the rule should be added, by default, rules are pushed at the end.
  • className add a rule with a predefined class name.

Add a rule dynamically

const rule = sheet.addRule({
  padding: 20,
  background: 'blue'
})
document.body.innerHTML = '<button class="' + rule.className + '">Button</button>'

Delete a rule from an existing Style Sheet

To remove a rule from the DOM, Style Sheet option link: true should be used. Returns true if rule has been removed from the DOM.

sheet.deleteRule(name)

Get a rule

sheet.getRule(name)

Access a rule within sheet by a name.

// Using name.
const rule = sheet.getRule('myButton')

Add multiple rules

sheet.addRules(styles)

In case you want to add rules to the sheet separately or even at runtime.

sheet.addRules({
  myButton: {
    float: 'left',
  },
  something: {
    display: 'none'
  }
})

Update function values

sheet.update(data)

If you use function values, you will want to update them with new data. This method will call all your function values, pass the data param and update the CSS Rule if needed.

sheet.update({
  // Any data here.
})

Create a rule without a Style Sheet

jss.createRule([name], style, [options])

In order to apply styles directly to the element but still be able to use jss s.

const rule = jss.createRule({
  padding: 20,
  background: 'blue'
})

const rule = jss.createRule('@media', {
  button: {
    color: 'red'
  }
})

Apply a rule to an element inline

rule.applyTo(element)

This is equivalent to element.style.background = 'blue' except that you could use a rule from sheet which is already defined. It uses rule.toJSON() internally, so same limitations are applied. Example.

jss.createRule({
  background: 'blue'
}).applyTo(element)

Set or get a rule property dynamically

rule.prop(name, [value])

When option link is true, after stylesheet is attached, linker saves references to CSSRule instances so that you are able to set rules properties at any time. Example.

const sheet = jss.createStyleSheet({
  a: {
    color: 'red'
  }
}, {link: true})

// Get the color.
sheet.getRule('a').prop('color') // red

// Set the color.
sheet.getRule('a').prop('color', 'green')

Convert rule to a JSON

rule.toJSON()

Returns JSON representation of a rule. Only regular rules are supported, no nested, conditionals, keyframes or fallbacks.

Result of toJSON call can be used later to apply styles inline to the element. It is used by rule.applyTo().

Convert to CSS

sheet.toString()

If you want to get a pure CSS string from JSS for e.g. when preprocessing server side.

import jss from 'jss'

const sheet = jss.createStyleSheet({
  button: {
    float: 'left'
  }
})

console.log(sheet.toString())
.button-d4f43g {
  float: left;
}

Generate your own class names

import {create} from 'jss'

const jss = create({
  generateClassName: (rule, sheet) => {
    return 'my-fancy-id'
  }
})

const sheet = jss.createStyleSheet({
  button: {
    float: 'left'
  }
})

console.log(sheet.toString())
.my-fancy-id {
  float: left;
}

Extract dynamic styles

getDynamicStyles(styles)

Extracts a styles object with only props that contain function values. Useful when you want to share a static part between different elements and render only the dynamic styles separate for each element.

const dynamicStyles = getDynamicStyles({
  button: {
    fontSize: 12,
    color: data => data.color
  }
})

// Returns only styles with dynamic values.
{
  button: {
    color: data => data.color
  }
}

Plugins

See plugins documentation.