JedWatson / classnames

A simple javascript utility for conditionally joining classNames together
MIT License
17.55k stars 557 forks source link

Access className by template literal string not working #272

Closed shiraz closed 2 years ago

shiraz commented 2 years ago

So I am trying to access a className based on a template literal string and it's not working.

WHAT WORKS: <div className={classNames(classes.box, classes.XYZcontentType)} />

WHAT DOES NOT WORK:

const prop = 'XYZ';
<div className={classNames(classes.box, classes[`${prop}contentType`])} />

I also tried:

const prop = 'XYZ';
 <div className={classNames( classes.box, { [`${prop}contentType`]: true } )} />

How can I get classNames to work with template strings that are generated dynamically?

Notes: I am using React.

newyork-anthonyng commented 2 years ago

@shiraz I created a demo in CodeSandbox. See here. The code works with a dynamically generate template string.

My guess is there's something wrong with your application code. Can you provide an example that reproduces the issue?

shiraz commented 2 years ago

@newyork-anthonyng I am using React. Can you create a sandbox with React instead?

shiraz commented 2 years ago

@newyork-anthonyng I made some changes to your sandbox to reflect the use of reactjss and classnames. Please have a look. Observe that the background style is not being applied.

shiraz commented 2 years ago

@newyork-anthonyng I made another sandbox. This is better one: https://codesandbox.io/s/react-jss-playground-forked-s7gsn1?file=/index.js Please observe line #45.

newyork-anthonyng commented 2 years ago

@shiraz I think you have a bug in your react-jss code.

const useStyles = createUseStyles({
  redWrapper: {
-    background: "red"
+    background: "red !important"
  },
  // ...
});

Does changing this get you what you wanted?

shiraz commented 2 years ago

@newyork-anthonyng Wow, that seemed to work but is there anyway to set the order correctly? Or it is it whatever react-jss decides?

newyork-anthonyng commented 2 years ago

@shiraz this is a react-jss and CSS question, and not relevant for this issue.