Messy Classnames Construction
Can anyone suggest a way to clean up this messy classname construction: const ButtonTemplate = props => { const themed = `btn-${props.theme}` const themedButton = `${styles[
Solution 1:
What about
functionButtonTemplate({theme, disabled, onClick, children}) {
const themed = `btn-${theme}`;
return (
<buttonclassName={[styles.btn,
styles[themed],
themed,
disabled ? 'disabled' : ''
].join(" ")} type='button'onClick={onClick}>{children}</button>
);
}
Solution 2:
Use the package classnames:
install:
npm install classnames
import:
import classNames from 'classnames';
use it :)
constButtonTemplate = props => {
const themed = classNames('btn-', props.theme)
const themedButton = classNames(
styles.btn,
styles[themed],
themed,
{ disabled: props.disabled }
);
return (
<buttonclassName={themedButton}type='button'onClick={props.onClick}>{props.children}</button>
)
}
It can be very helpful as we will be facing similar situations throughout developing a big project. Here are some tricks copied from the original documentation:
classNames('foo', 'bar'); // => 'foo bar'classNames('foo', { bar: true }); // => 'foo bar'classNames({ 'foo-bar': true }); // => 'foo-bar'classNames({ 'foo-bar': false }); // => ''classNames({ foo: true }, { bar: true }); // => 'foo bar'classNames({ foo: true, bar: true }); // => 'foo bar'// lots of arguments of various typesclassNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'// other falsy values are just ignoredclassNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
...and there are more. You should really take a look at it and give it a try.
Solution 3:
constButtonTemplate = props => {
const { children, disabled, onClick, theme } = props;
const disabled = disabled ? 'disabled' : '';
const themed = `btn-${theme}`const className = `${styles.btn}${styles[themed]}${themed}${disabled}`;
return (
<buttonclassName={className}type='button'onClick={onClick}>{children}</button>
)
}
Post a Comment for "Messy Classnames Construction"