reject:dynamic_classname

Dynamic className

Another way to do dynamic styling is through changing the class name directly. Here is how we change the className of a div (with className={myDivClasses}) dynamically based on prop.index. After all, className is just a string with names that spereated by a space.

import React from "react";
import './ItemComponent.css';

const ItemComponent = (prop) => {
    let myDivClasses = 'margin5px';
    if (prop.index % 2 === 0) {
        myDivClasses = myDivClasses + " myEvenDiv";
    } else {
        myDivClasses = myDivClasses + " myOddDiv";
    }
    return (
        <div className={myDivClasses}>
            <span key={prop.index}
                  onClick={prop.clickHandler}>
                name: {prop.name}, price: ${prop.price}, key: {prop.index}</span>
        </div>
    );
};

export default ItemComponent;

The css file:

.myOddDiv {
    background-color: sandybrown;
}

.myEvenDiv {
    background-color:#61dafb;
}

.margin5px {
    margin: 5px;
}
  • reject/dynamic_classname.txt
  • Last modified: 2020/07/14 10:35
  • by chongtin