cssreactjsclass-names

How to use classnames lib with conditional and dynamic classes


I started using classnames lib and it's pretty simple and neat until I hit this case.

I want to make an expandable row animation. Idea is simple - conditionally add class that would add animation to the open row. The hight of the expanded row is dynamic in my case.

Here's my simplified React component

// some code

const expanded = {
    maxHeight: heightProp,
    transition: 'max-height 1s ease-out';
  };

  const expandable = classnames({
    [styles.expandableContainer]: true,
    [expanded]: isExpanded,
  });

return (
   <tr ref={rowRef} className={expandable}></td>
)

// some code

CSS file

.expandableContainer {
    max-height: 0;
    overflow: hidden;
    transition: max-height 1s ease-in;
}

For right now it gives me as a result class="expandableContainer [object Object]" in expanded state. Where's the issue here? Why it's objectObject?

If this heightProp wouldn't be dynamic it would be just

const expandable = classnames({
    [styles.expandableContainer]: true,
    [styles.expanded]: isExpanded,
  });

But looks like I don't know how to deal with css defined inside a component.

Thanks a lot for the help!


Solution

  • ok the answer would be don't use classnames, use just

    <tr className={styles.expandableContainer} style={isExpanded ? expanded : null}></tr>