rock_n_rolla
rock_n_rolla

Reputation: 357

Conditionally applying className to a react component depending on where the component is used

Let's say I have two components ThisComponent and ThatComponent. Inside those components, I render a third component ACoolThirdComponent. What I'm trying to achieve is set the class of the div depending on whether I use the ACoolThirdComponent in ThisComponent or ThatComponent.

Is this possible?

ThisComponent

export const ThisComponent = () => {

   return (
      <ACoolThirdComponent/>
   )

}

ThatComponent

export const ThatComponent = () => {

    return (
        <AThirdCoolComponent/>
    )

}

Then, the last third ACoolThirdComponent

export const ACoolThirdComponent = () => {

    /* Psuedo code */ 

    if this component is used-in/called from ThisComponent set a class "this-cool-class"
    if this component is used-in/called from ThatComponent set a class "that-awesome-class"

    return ( 
      <div className={aNiceDynamicClassBasedOnTheAbove}></div>
    )
  }

Upvotes: 1

Views: 23

Answers (1)

Carlos Saiz Orteu
Carlos Saiz Orteu

Reputation: 1805

Try it passing a prop so you can detect it:

export const ACoolThirdComponent = ({ className }) => {



    return ( 
      <div className={className}></div>
    )
  }

So when you call it you can pass him the className you want:

export const ThatComponent = () => {

    return (
        <AThirdCoolComponent className="whatever"/>
    )

}

Upvotes: 1

Related Questions