<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');
}}
/>
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}
/>
);
}
npm install --save-dev babel-plugin-jsx-merge-props
.babelrc
:
{
"plugins": [ "babel-plugin-jsx-merge-props" ]
}
- merge-props: Merges className, style, and event handler props for React elements