Home > OS >  understanding JS6 template literals for making dynamic CSS classNames
understanding JS6 template literals for making dynamic CSS classNames

Time:06-08

these days I try to learn full-stack dev skills. After several courses we got introduced to React. The overall used system is a localhost npm Server, with installed React. Later we will install Mongo and Express.

Topic of the lesson is, some kind of Webshop with 2 tabs: Items and Cart in the Navbar and automatic filled list either with the shop items, or the chosen user Cart items.

The Navbar in the header consists of 2 <li-<button "Items" / "Cart" elements. These elements shall earn their className dynamically, based on the global hook const activeTab. Syntax is following:

 const Nav = ({activeTab, onTabChange}) => {
    const itemClass = tabName => 
        `App-nav-item ${ 
            activeTab === tabName ? 'selected': '' 
        }`;
    return (
    <nav className="App-nav">
        <ul>
            <li className={itemClass('items')}>

###

I understand, that itemClass is a template literal of the string 'App-nav-item' and the String 'selected' or ''. Results should be App-nav-itemselected or App-nav-item

But the result is App-nav-item.selected ! Why? In CSS I have to adress App-nav-item.selected, I dont understand that. For any information I would be grateful :).

Thanks!

CodePudding user response:

Results should be App-nav-itemselected or App-nav-item

No. There is a space between App-nav-item and ${...}. It will be App-nav-item selected or App-nav-item.


The className property maps to the class attribute which accepts a space-separated list of class names.


In a selector, when writing multiple selectors (be they type selectors, class selectors, attribute selectors, other selectors, or a mix of any of the above) which target the same element, they are simply mashed together.

.foo.bar

In short: Different language = Different syntax.

  • Related