dagda1
dagda1

Reputation: 28870

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[themed]} ${themed}${(props.disabled) ? ' disabled' : ''}}`

  return (
    <button className={`${styles.btn} ${themedButton}`} type='button' onClick={props.onClick}>{props.children}</button>
  )
}

Upvotes: 1

Views: 204

Answers (3)

yadhu
yadhu

Reputation: 15642

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.

Upvotes: 1

Bergi
Bergi

Reputation: 664980

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>
  );
}

Upvotes: 5

kjonsson
kjonsson

Reputation: 2799

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>
  )
}

Upvotes: 0

Related Questions