1
votes

I have modular component using css module as styling method, let's say component.js and component.module.scss. what I want to achieve is to use the component with className as prop.


// component.js

import React from 'react';
import Style from './grid.module.scss';

const Grid = (props) => {
    return(
        <div className={`${Style[props.test]}`}>
            {props.children}
        </div>
    )
}

export default Grid;
// component.module.scss

.foo {
  // some style here...
}

.bar {
  // some style here...
}

The problem is that Style[props.test] doesn't work if the props has more than one class name.

For example

// index.js

import React from 'react';
import Grid from './component';

// Working
<Grid test="a">Baz</Grid> // the output is class="a--3ofml"

// doesnt work
<Grid test="a b">Baz</Grid>  // the output is class="undefined"

How to have code that working with multiple props value?

2

2 Answers

3
votes

Looks like you can do something like this:

return (
   <div className={
      props.test.split(' ').map(s => `${Style[s]}`).join(' ')
    }>
      {props.children}
   </div>
)

Used this as a reference.

0
votes
const Grid = (props) => {
    let cls = props.test.split(" ");
    let styleNames = "";
    cls.forEach(el => {
        styleNames = styleNames + Style[el] + " ";
    })
    return (
        <div className={styleNames}>
            {props.children}
        </div>
    )
}