Skip to content Skip to sidebar Skip to footer

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

function ButtonTemplate({theme, disabled, onClick, children}) {
  const themed = `btn-${theme}`;
  return (
    <button className={[
      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 :)

const ButtonTemplate = props => {
  const themed = classNames('btn-', props.theme)
  const themedButton = classNames(
    styles.btn,
    styles[themed],
    themed,
    { disabled: props.disabled }
  );

  return (
    <button className={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 types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(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:

const ButtonTemplate = props => {
  const { children, disabled, onClick, theme } = props;

  const disabled = disabled ? 'disabled' : '';
  const themed = `btn-${theme}`
  const className = `${styles.btn} ${styles[themed]} ${themed} ${disabled}`;

  return (
    <button className={className} type='button' onClick={onClick}>{children}</button>
  )
}

Post a Comment for "Messy Classnames Construction"