Home > other >  Add/remove class name in react obj?
Add/remove class name in react obj?

Time:09-01

How to add/remove class without knowing the base class components ?

<Img variant="top" class={isImageOn ?  '': 'd-none'} src={dp} />

I just want to add/remove d-none class to the <Img/> object based on the bool var. In this example here it is setting the class to null if isImageOn is true. Can someone help on this please ?

CodePudding user response:

The component Img has to provide a way to allow customization of the classes of the element that will be rendered. (You cannot add/remove class in an absolue generic way/without knowing the interface of the component you are using)

A basic way Img can allow customization:

const Img = ({ className, ...props }) => {
  return (
    <img {...props} className={`... ${className || ''}`} />
  );
}

CodePudding user response:

If its react jsx it should work, just change class for className

<Img variant="top" className={isImageOn ?  '': 'd-none'} src={dp} />

CodePudding user response:

From React DOCs class is a reserved word ( since class is JS is used for OOP )

enter link description here So you can do like this:

<Img variant="top" className={isImageOn ?  '': 'd-none'} src={dp} />
  • Related