Search code examples
javascriptcssreactjstypescriptclsx

How to use clsx in nested components in React


I'm using clsx in a React application and I have an issue on how to use it when there are mappings and nested components.

For example:

return ( 
  <div>
    <button onClick={doSomething}>{isOpened ? <Component1 /> : <Component2 />}</button>
    <div className={clsx(containerClasses)}>
        {myData.map((item, index) =>
          <OuterComponent as='div' key={item.name}>
            {({ open }) =>
              <>
                <InnerComponent
                  className={}// how to compute this value?
                >

Above we have a returned JSX, an outer div element, a value isOpened which comes from the state so we have access to it everywhere. This means we can implement the following containerClasses:

const containerClasses = {
    'class1 ': true,
    'class2': isOpened,
    'class3': !isOpened
  };

All good until here.

But as you can see, there is myData.map(...) which iterates through an array. Here, I would need to compute innerClasses based on the value of open. But this value is accessible just inside the loop, not outside the return and inside the function.

Is there a way to solve this problem with clsx?


Solution

  • const getClasses= (open) => {
      return clsx({
         [classes.class1]: open, // desired classname and condition
      })
    }
    
    <InnerComponent
        className={getClasses(open)} //call a method here
    >