I have an image where the CSS class on the image needs to be change dynamically. It is passed in dynamically from this object from the key "size":
export const decals = [
{ label: 'Nikola Tesla', img: `/images/decals/tesla.svg`, size: `decalMed` },
{ label: 'Tattoo Mom Heart', img: `/images/decals/ARF149.svg`, size: `decalSm`}
Into another component here:
import styles from ./Shirt.module.css';
<img key={decals[decal].label} src={decals[decal].img} alt={decals[decal].label} className={`${styles}.${decals[decal].size}`}/>
The className= is the issue. I've tried so many different ways to pass this class.
I've captured this (decals[decal].size) into a variable before passing to the image tag. I've tried to use the style tag instead of className and created a variable to hold the class. I've changed around the brackets. I've tried passing it into an outside div.
Nothing seems to work.
I'm wondering if anyone can clue a react newbie in. Thank you!
if I am not wrong, you trying to dynamically manage classes that are passing through to the image element.To do that, I recommend you to use "classnames" https://www.npmjs.com/package/classnames
With this package, you can control classNames with variables in your component. I will try explain usage with a little example.
Your style file like
.yourParentClass {
&.decalMedClass {
// your styles for this class
}
&.decalSmClass {
// your styles for this class
}
}
your component file like
import Style from '../style.scss'; // Your classes
var classNames = require('classnames/bind'); // classname package
const cx = classNames.bind(Style);
// your code
render() {
return (
<img className={
cx({
yourParentClass: true,
decalMedClass: this.state.sizeMed,
decalSmClass: !this.state.sizeMed,
})
}
/>
);
}
Basically, you telling that which class gonna be active. Please do not stick with my example, there are good examples on the npm page.