Steven Bennett
Steven Bennett

Reputation: 309

Template string literal inside of another template string literal

So the code I have currently, works, but I'm receiving the prefer-template: Unexpected string concatenation ESLINT error, which I'd like to avoid by perhaps knowing the correct way to do this with template strings literals.

Here's the code I have now:

<div className={`${styles.dataGridHeader} ${styles['columns' + this.props.data.headers.length]}`}>

I want to apply a class column1, column2, column3, etc, depending on the number of columns in the data report, so that I can apply some specific styling to those elements.

What I have works, but is there a way to avoid using concatenation and only use template string literals?

For example:

<div className={`${styles.dataGridHeader} ${styles[`columns${this.props.data.headers.length}`]}`}>

Super ugly, and doesn't work, would love a more elegant solution.

Upvotes: 1

Views: 12887

Answers (1)

Mauricio Poppe
Mauricio Poppe

Reputation: 4876

How about this

const nColumn = 'columns' + this.props.data.headers.length
<div className={`${styles.dataGridHeader} ${styles[nColumn]}`}>

FYI there's an awesome library called classnames which applied to your code it looks something like this

import classNames from 'classnames'
const nColumn = 'columns' + this.props.data.headers.length
const divCls = classNames({
  [`${styles.dataGridHeader}`]: true,
  [`${styles[nColumn]}`]: true
})
<div className={divCls} />

Upvotes: 4

Related Questions