How to concatenate values within a class in React.JS

Asked

Viewed 2,746 times

1

I have the following code:

{
    this.state.listSkills.map(function(habilidade){
    return (
        <ul className="habilidades">                                            
            <li className="habilidade-"{habilidade.value}>
                <h2>{habilidade.name}
                <div className="barra"><span></span></div>
                </h2>
            </li>
        </ul>
        );
    })
}

The value of the variable habilidade.value comes from a dynamic json with a value and a percentage symbol (%), example: 10%.

I need to concatenate the string "habilidade" with this variable and take the % to keep class="habilidade-10". How to do?

  • Where exactly you need this value?

  • in Sass, so I can use it when it is rendered @for $i from 0 through 100{ li.ability-#{$i}{ . barra{ span{ width: 1% * $i; } } }

  • 1

    Try className={"habilidade-" + habilidade.value.replace('%', '')}

  • It worked, thank you very much!

  • I created an answer to help other users who have the same problem in the future. If you can, mark it as correct.

1 answer

1


In React, you can use javascript codes within component properties using the keys ({}).

This is very useful when you need to concatenate values or call functions.

With this, to concatenate the "habilidade-" with the habilidade.value on the property className, you can do it this way:

className={"habilidade-" + habilidade.value}

To take the value of % you can replace the string, so:

className={"habilidade-" + habilidade.value.replace('%', '')}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.