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?

1
  • 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. Commented Jan 29, 2019 at 10:24

5 Answers 5

1

Correct syntax would be:

You can use interpolation syntax from ES6.

<div className={`module module--${this.props.classModifier}`}></div>
Sign up to request clarification or add additional context in comments.

2 Comments

Not typically in React projects (for this specific example), although it does work. (Adding "why" would be good, too.)
To plagiarise @T.J.Crowder "Why" would be a very useful extension to your answer.
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}

Comments

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}.

Comments

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}`}

Comments

0

you need change code to this:

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

1 Comment

@Ionut - Ah yes. (Huh, normally I do check for edits...)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.