1

I have a basic component that I'd like to use in multiple instances with differing classes.

 <div className="module module--{this.props.classModifier}" ></div>

When I render the above using <...classModifier="red" /> it doesn't affect what is rendered and the browser outputs {this.props.classModifier}

Can anybody point out where and what I'm doing wrong?

Liam
  • 9,725
  • 39
  • 111
  • 209
  • The main reason why this happens is because the `{this.props.classModifier}` is treated as string instead of a variable. You have options. You can use **concatenation** or **interpolation**. – Ionut Necula Jan 29 '19 at 10:24

5 Answers5

1

This syntax will be treated as a pure string: "module module--{this.props.classModifier}". If you want to append string using JSX, try this syntax instead className={"module module--" + this.props.classModifier}.

Hai Pham
  • 2,188
  • 11
  • 20
1

Correct syntax would be:

You can use interpolation syntax from ES6.

<div className={`module module--${this.props.classModifier}`}></div>
Jitesh Manglani
  • 495
  • 5
  • 12
  • 1
    Not typically in React projects (for this specific example), although it *does* work. (Adding "why" would be good, too.) – T.J. Crowder Jan 29 '19 at 10:19
  • To plagiarise @T.J.Crowder "Why" would be a very useful extension to your answer. – Liam Jan 29 '19 at 10:21
1

As an explanation, if you use double quotes only, you're just rendering a string. It won't get the variable reference like that. You have to split the variable and the string portions by wrapping it with the curly braces:

//Template Literals
className={`module module--${this.props.classModifier}`}

//Concatenation
className={"module module--" + this.props.classModifier}
Keno
  • 2,018
  • 1
  • 16
  • 26
0

you need change code to this:

<div className={`module module--${this.props.classModifier}`}></div>
Behnam
  • 6,244
  • 1
  • 39
  • 36
0

You are using this.props.classModifier inside a "" so it will print as it is. Use template strings
Use this

 className={`module module--${this.props.classModifier}`}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73