Skip to content

samtietjen/mapped-system

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mapped System

React style props that render consistent class names
Introduction : Installation : Usage : Packages : Credits : License

Introduction

Mapped System is a library for creating React elements that render class names from props. It takes a simple, easy-to-maintain, rules-based approach without tedious logic. Try it out on CodeSandbox!

Installation

npm i mapped-system

Usage

Create a component by pairing props (i.e. size) with class names (i.e. box-size).

import PropTypes from 'prop-types';
import useMapper from 'mapped-system';

const Box = useMapper({
  size: 'box-size'
});

Box.propTypes = {
  size: PropTypes.any
}

Props will append values to their class names.

<Box size={1} />
// Segments are separated by a dash.
// <div class="box-size-1"></div>

<Box size="100%" />
// Percentage signs convert to `p`.
// <div class="box-size-100p"></div>

<Box size={2.5} />
// Floats round to the nearest integer.
// <div class="box-size-3"></div>

<Box size={1/3} />
// Numbers between `0` and `1` convert to percentages.
// <div class="box-size-33p"></div>

<Box size={true} />
// Booleans add the class name while `true`.
// <div class="box-size"></div>

<Box size={{large: true, children: 1}} />
// Objects prefix keys to values.
// <div class="box-size-large box-size-children-1"></div>

<Box size={[1, 2, 3]} />
// Arrays prefix breakpoints `md` and `lg` at indexes `1` and `2`.
// <div class="box-size-1 md-box-size-2 lg-box-size-3"></div>

<Box size={() => 1 + 2} />
// Functions return their output.
// <div class="box-size-3"></div>

Advanced

Functions can be used to handle complex mappings.

const Box = useMapper({
  size: n => 'size-' n + '-box'
});

<Box size={1} />
// As a mapping it will pass its value as an argument.
// <div class="size-4-box"></div>

Utilities

Each component includes base, blacklist, and tag utilities.

<Box base="box" size={1} /> 
// Prepend a class to the class list.
// <div class="box box-size-1"></div>

<Box blacklist={['href']} href="#" /> 
// Block attributes from an element.
// <div></div>

<Box tag="h2" /> 
// Transform the HTML tag.
// <h2></h2>

Extending

Components maintain mappings and propTypes.

const Section = useMapper({
  ...Box.mappings
});

Section.propTypes = {
  ...Box.propTypes
}

Section.defaultProps = {
  tag: 'section'
}

Packages

Package Stability Description
Mapped Components Experimental React components that render class names from props
Mapped Classes Stable Convert objects into consistent class name strings

Credits

Inspired by Styled System.

License

MIT © Sam Tietjen

About

React style props that render consistent class names

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages