0

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;

1 Answer 1

1

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>;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it's working. Is there any established way to use styles and classes that most of the react developers are following?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.