Search code examples
reactjscss-moduleswebpack-style-loader

How to dynamically pass multiple classes to child component using CSS modules in React


I am new to React.js. I am using CSS modules for styling and I want to dynamically pass multiple classes to a child component. Below is my code.

Parent component

Here I am passing p-1 color-red to child component.

import React, { Component } from 'react';
import Demo from '../../shared/Demo';

class App extends Component {
  state = {
      headerClass: 'p-1 color-red'
    }
  }
  render() {
    return (
      <Demo headerClass={this.state.headerClass}>
      </Demo>
    );
  }
}

export default App;

Child component

Since, class name is dynamic and there are more than one classes I am not sure how to access it here. Below code is working if I have only one class in headerClass.

import React from "react";
import styles from './Demo.css';

const demo = (props) => {
  return (
    <div className={styles[props.headerClass]}>{ props.title }</th>
  );
}

export default demo;

Solution

  • You can split the headerClass string property and concatenate all class names.

    const demo = (props) => {
      const reducer = (acc, curr) => `${acc} ${styles[curr]}`;
      const className = props.headerClass.split(' ').reduce(reducer, '');
      return <div className={className}>{ props.title }</div>;
    }