Home > Mobile >  React / How to assign a variable to a classname property
React / How to assign a variable to a classname property

Time:09-03

Hello

In the following code I have tried to assign the variable classNameDiv to a classname, but it doesn't work. Strangely double curly brackets works for the style property just below

return (
  <div className="item" key={i}>
    <img src={`./images/${myjson.images[index].name}`} alt="" />
    <div className="allBoxes">
      {myjson.images[index].palette.map((index2, j) => {
        const b = myjson.images[index].palette[j]
        const classNameDiv = "colorBox";
        if (RefArrayPalette[index][j] === 1) {
          classNameDiv = "colorBox2";//_________________first here___________
        }
        return (
          <div
            key={j}
            //className="colorBox"
            className={{classNameDiv}}  //____________________then here_____________
            style={{ backgroundColor: index2 }}
            onClick={calculateNewList}
          />
        )
      }, (i, index))}

CodePudding user response:

In your example className is a const so it not reassignable, you should use let

div className props is expected to be a string

className={{classNameDiv}} actually mean you are passing the object { classNameDiv: classNameDiv } as className prop

What you should do is className={classNameDiv}

CodePudding user response:

The className property expects a string, but you're passing it an object:

className={{classNameDiv}}

Just pass it the string value:

className={classNameDiv}

Strangely double curly brackets works for the style property just below

Because the style property expects an object. It's not really "double curly braces", it's an object literal (which uses curly braces) inside of a JSX property (which uses curly braces).

  • Related