Git Product home page Git Product logo

obj-str's Introduction

obj-str CI codecov

A tiny (96B) library for serializing Object values to Strings.

This module's intended use is for converting an Object with CSS class names (as keys) to a space-delimited className string. Other modules have similar goals (like classnames), but obj-str only does one thing. This is why it's only 100 bytes gzipped!

PS: I made this because Preact 8.0 removed this built-in behavior and I wanted a quick, drop-in replacement.

Install

$ npm install --save obj-str

Usage

import objstr from 'obj-str';

objstr({ foo:true, bar:false, baz:isTrue() });
//=> 'foo baz'

React

With React (or any of the React-like libraries!), you can take advantage of any props or state values in order to express conditional classes as an object.

import React from 'react';
import objstr from 'obj-str';

const TodoItem = ({ text, isDone, disabled }) => (
  <li className={ objstr({ item:true, completed:isDone, disabled }) }>
    <input type="checkbox" disabled={ disabled } checked={ isDone } />
    <label>{ text }</label>
  </li>
);

Preact

For simple use, the React example will work for Preact too. However, you may also define a custom vNode "polyfill" to automatically handle Objects when used inside className.

Note: For users of Preact 7.1 and below, you do not need this module! Your version includes this behavior out of the box!

import objstr from 'obj-str';
import { options } from 'preact';

const old = options.vnode;

options.vnode = vnode => {
  const props = vnode.attributes;
  if (props != null) {
    const k = 'class' in props ? 'class' : 'className';
    if (props[k] && typeof props[k]=='object') {
      props[k] = objstr(props[k]);
    }
  }
  old && old(vnode);
}

API

objstr(input)

input

Type: Object

A hashmap of keys & their truthy/falsey values. Booleans are preferred when speed is critically important.

Related

  • babel-plugin-optimize-obj-str - Babel plugin to transform obj-str calls into optimized expressions.

  • clsx - Drop-in replacement for obj-str and classnames โ€“ handles all (and multiple) input types.

License

MIT ยฉ Luke Edwards

obj-str's People

Contributors

alanorozco avatar frederikhors avatar lukeed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

obj-str's Issues

Breaks on IE 11

Bug
IE 11 does not support const in for loops.

The rollup generated code has const instead of var.

Fix
The rollup build has to generate code using a transpiler like babel

ES Version

What is the minimum version of ES that is required?

Because we can make that even more tiny like this:

export default (obj = {}) => Object.keys(obj).filter(k => obj[k]).join(' ');

Babel plugin error: ".strict is not a valid Plugin property"

I'm using this lib but only today I found it's babel plugin: amazing!

With @rollup/plugin-babel it throws using it like this:

  • rollup.config.js:
import { babel } from "@rollup/plugin-babel";
import { terser } from "rollup-plugin-terser";

export default {
  //...
  plugins: [
    babel({
      babelHelpers: "bundled",
      extensions: [".svelte"],
      plugins: ["optimize-objstr", { "strict": true }],
    }),
  ],
};

the error:

Error: [BABEL] C:\a\src\App.svelte: .strict is not a valid Plugin property
- Maybe you meant to use
"plugin": [
  ["optimize-objstr", {
  "strict": true
}]
]
To be a valid plugin, its name and options should be wrapped in a pair of brackets
    at C:\a\node_modules\@babel\core\lib\config\validation\plugins.js:65:42
    at Array.forEach (<anonymous>)
    at validatePluginObject (C:\a\node_modules\@babel\core\lib\config\validation\plugins.js:54:20)
    at C:\a\node_modules\@babel\core\lib\config\full.js:261:55
    at Generator.next (<anonymous>)
    at Function.<anonymous> (C:\a\node_modules\@babel\core\lib\gensync-utils\async.js:16:3)
    at Generator.next (<anonymous>)
    at step (C:\a\node_modules\gensync\index.js:261:32)
    at evaluateAsync (C:\a\node_modules\gensync\index.js:291:5)
    at Function.errback (C:\a\node_modules\gensync\index.js:113:7)

Why?

Using it with Svelte: undefined values

I'm using obj-str with Svelte.

This is an example: https://svelte.dev/repl/8ed7006e598e48b3a5083bf6c6abe3f4?version=3.35.0.

  • Component.svelte:
<script>
	let className
	export { className as class }

	function objstr(obj) {
		var k;
		var cls = ""
		for (k in obj) {
			console.log("k:", k, "v:", obj[k])
			if (obj[k]) {
				cls && (cls += " ")
				cls += k
			}
		}
		return cls
	}

	$: klass = objstr({
		"default": true,
		// [className]: className != null,
		// [className]: !!className,
		// className: className != null,
		[className]: className,
	});
</script>

<div class={klass}>klass: {klass}</div>

QUESTIONS:

  1. Which method is faster between

    1. [className]: className != null and
    2. [className]: !!className ?
  2. As I'm new to javascript I also noticed that these two methods don't work, right?

    1. className: className != null
    2. [className]: className

    They both return className instead of className value, even after the toggle() call, why?

Maybe we can add Svelte instructions to Readme.

create-react-app won't build when depending on obj-str

This is a weird one, and I bet this isn't the right place for it. Running yarn build in my create-react-app project, it fails with:

$ react-scripts build
Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

        ./node_modules/obj-str/dist/obj-str.es.js:2 

Read more here: http://bit.ly/2tRViJ9

error Command failed with exit code 1.

Following the link, it recommends filing an issue, even though I don't see why this isn't working.

My dependencies are:

"axios": "^0.16.2",
"date-fns": "^1.28.5",
"immutability-helper": "^2.4.0",
"lodash": "^4.17.4",
"normalize.css": "^7.0.0",
"obj-str": "^1.0.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^5.0.6",
"react-scripts": "1.0.14",
"redux": "^3.7.2",
"redux-devtools-extension": "^2.13.2",
"redux-thunk": "^2.2.0",
"reselect": "^3.0.1"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.