Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Templating for object keys

Tags:

I'm getting eslint error Unexpected string concatenation.eslint(prefer-template)

const listItemClasses = classNames({
          [' ' + classes[color]]: activeRoute(props, prop.layout + prop.path),
    });

How to fix this with template literals `` or shall I need to update eslint rule to allow this?

like image 257
user2473015 Avatar asked Feb 28 '19 10:02

user2473015


People also ask

What are template strings?

Template literals are literals delimited with backtick ( ` ) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.

What is `` in JS?

Backticks ( ` ) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier. Features: we can interpolate any kind of expression in the template literals. They can be multi-line.

What is ${} in HTML?

The ${} syntax allows us to put an expression in it and it will produce the value, which in our case above is just a variable that holds a string! There is something to note here: if you wanted to add in values, like above, you do not need to use a Template Literal for the name variable.

Does Java have template strings?

A string template expression is a new kind of expression in the Java programming language. A string template expression can perform string interpolation, but is also programmable in a way that helps developers compose strings safely and efficiently.


1 Answers

The eslint rule prefer-template expects you not to concatenate strings, and only use template strings.

In your case, you need to replace

' ' + classes[color]

with

` ${classes[color]}`

IIRC, eslint has an "auto-fix" flag for fixing that kind of error.

Also, the eslint plugin for Visual Studio Code has the auto-fix built-in.

like image 63
Seblor Avatar answered Sep 22 '22 16:09

Seblor