I am trying to reference data attributes from JSS, test for them, and apply the styles if the test is true. However, when I run the code below, it does not apply "color:green" and I have no idea why!
import React from "react";
import { createUseStyles } from "react-jss";
const useStyles = createUseStyles({
statusDiv: {
backgroundColor: "lightGrey",
padding: "10px",
fontWeight: "bold",
'[data-status="OPEN"]': {
// no effect ..?
color: "green",
},
},
});
const App = () => {
const classes = useStyles();
return (
<div data-status="OPEN" className={classes.statusDiv}>
OPEN
</div>
);
};
export default App;
That's an interesting case. What you can do is:
export default {
'@global' : {
'div.testClass[data-custom="value"]': {
color: 'red',
border: '1px, solid navy'
}
}
}
This assumes a JSS plug-in @global installed, but this is something I think is quite useful to have. More about the plug-in @global - here
And if you want to address a data- attribute like in your edited example 0 you should do:
testClass: {
'[data-custom="value"]': {
//styles for the custom data
}
}
And in the markup you'll have (depends on the way you extracting the class):
testClass.classes['[data-custom="value"]']
... styles for the custom data will be applied by the above.
The way you wrote in your last edit will not work. You should add a small bit though. To work the code example you provided:
...
fontWeight: "bold",
'& [data-status="OPEN"]': {
// no effect ..?
color: "green",
},
The & require a nesting plug-in setup - here is more about it.
If your JS looks like this:
<div data-customAttribute={value} className={classes.testClass}></div>
Your CSS will look like:
.testClass[data-customAttribute="value"] {
// your styles
}
Thanks to the amazing support from @Vladyn, the following code demonstrates this working perfectly:D
import React from "react";
import { create } from "jss";
import { JssProvider, createUseStyles } from "react-jss";
import nested from "jss-plugin-nested";
const jss = create();
jss.use(nested());
const useStyles = createUseStyles({
statusDiv: {
backgroundColor: "lightGrey",
padding: "10px",
fontWeight: "bold",
'&[data-status="OPEN"]': {
color: "green",
},
'&[data-status="CLOSED"]': {
color: "red",
},
},
});
const App = () => {
const classes = useStyles();
const status = "OPEN";
return (
<JssProvider jss={jss}>
<div data-status={status} className={classes.statusDiv}>
{status}
</div>
</JssProvider>
);
};
export default App;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.