Home > database >  Insert variable in className to check the true/false condition
Insert variable in className to check the true/false condition

Time:05-28

I make a Gutenberg block based on React and I have a className:

<div className={`wp-block-multiple-blocks-gb-button__btn ${gbButtonWidth} full-width`}>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I have a variable "gbButtonWidth" which is responsible for toggle and changing the true/false condition.

Here, when you click on toggle, when true should add to this class:

`wp-block-multiple-blocks-gb-button__btn`

extra class:

`full-width`

and remove it if you click on toggle and false is triggered.

The toggle is done, true/false works.

I only have a problem with adding an extra class to the current class by checking $variable

CodePudding user response:

you can add an argument (variable value) in the handleClick function

...
 onclick="handleClick(gbButtonWidth)"

and

based on its value you can add/remove class

function handleClick(value) {
        let elem = document.querySelector(".text");

        if (value) { /// add full-width when variable is true
           elem.classList.add("full-width");
        } else {
           /// remove full-width when variable is false
           elem.classList.remove("full-width");
 }
      }
function handleClick(value) {
        let elem = document.querySelector(".text");

        if (value) { //

    function handleClick() {
        let elem = document.querySelector(".text");

        if (elem.classList.contains("toggle")) {
          elem.classList.remove("toggle");
        } else {
          elem.classList.add("toggle");
        }
      }
.text{
color: red
}
.toggle{
background:green
}
<button onclick="handleClick()">
Click ME
</button>
<h1 >Hello</h1>

CodePudding user response:

<div className={`wp-block-multiple-blocks-gb-button__btn ${gbButtonWidth ? 'full-width' : ''}`}>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

  • Related