Home > OS >  passing a dynamic class name as a prop in react
passing a dynamic class name as a prop in react

Time:10-11

I am trying to make a modal toggle between visible and invisible by applying an invisible or visible class to the surrounding div of the component. In the App component I am using state to pass the className dynamically like this :

 ` <Modal newClass={modalState ? "visible" : "invisible"} /> `

and I am trying to apply that style to the Modal component like this:

<div className={styles.${props.newClass}}>

I am using a module for the css file importing "styles" from "./Modal.module.css" and when I inspect the element on the web browser the class name comes out as "styles.invisible" or "styles.visible" instead of the dynamic name the module is supposed to create. Is there a better way to do this or is there a way to fix this problem? Any help would be appreciated thank you.

CodePudding user response:

I suggest to just pass visible/invisible as prop and according to this prop choose style from module:

<Modal visible={true} />
const Modal = ({visible})=>{

return <div className={visible ? styles.visible : styles.invisible} />
}

CodePudding user response:

Easiest method would be to use a ternary operator in the className to get the required class. So instead of passing the className as prop, you can pass the modalState to Modal

Modal visible={modalState} />
<div className={visible ? styles.visible : styles.invisible}>

If you have more than one classes which depend upon a condition, I would recommend using clsx

  • Related