Skip to content

Latest commit

 

History

History
147 lines (122 loc) · 2.87 KB

README.md

File metadata and controls

147 lines (122 loc) · 2.87 KB

babel-plugin-jsx-merge-props

Build Status codecov npm

<div
  merge={mergeProps}
  className="foo"
  className="bar"
  style={{ color: 'red' }}
  style={{ backgroundColor: 'blue' }}
  onClick={() => console.log('foo')}
  onClick={() => console.log('bar')}
/>

become to

<div
  {...mergeProps(
    { className: 'foo' },
    { className: 'bar' },
    { style: { color: 'red' } },
    { style: { backgroundColor: 'blue' } },
    { onClick: () => console.log('foo') },
    { onClick: () => console.log('bar') }
  )}
/>

This will works like

<div
  className="foo bar"
  style={{ color: 'red', backgroundColor: 'blue' }}
  onClick={() => {
    console.log('foo');
    console.log('bar');
  }}
/>

Why?

It's annoying to use props that provided from multiple hooks.

const useFirstHook = () => {
  ...

  return {
    className,
    style,
    onClick,
  };
};

const useSecondHook = () => {
  ...

  return {
    value,
    style,
    onClick,
  };
};
const MyComponent = () => {
  const first = useFirstHook(...);
  const second = useSecondHook(...);

  const handleClick = useCallback(event => {
    first.onClick(event);
    second.onClick(event);
  }, [first, second]);

  return (
    <input
      type="text"
      {...first}
      {...second}
      className={[first.className, second.className].join(' ')}
      style={{ ...first.style, ...second.style }}
      onClick={handleClick}
    />
  );
}

Or would be better to use some package like merge-props, but It's still little bit bothersome.

import mergeProps from 'merge-props';

const MyComponent = () => {
  const first = useFirstHook(...);
  const second = useSecondHook(...);

  return (
    <input
      type="text"
      {...mergeProps(first, second)}
    />
  );
}

You can just write like below with this plugin.

import mergeProps from 'merge-props';

const MyComponent = () => {
  const first = useFirstHook(...);
  const second = useSecondHook(...);

  return (
    <input merge={mergeProps}
      type="text"
      {...first}
      {...second}
    />
  );
}

Installation

npm install --save-dev babel-plugin-jsx-merge-props

Usage

.babelrc:

{
  "plugins": [ "babel-plugin-jsx-merge-props" ]
}

Related

  • merge-props: Merges className, style, and event handler props for React elements