Home > database >  How to create on/off switch for a piece of code?
How to create on/off switch for a piece of code?

Time:09-09

I am pretty new at coding and I'm tinkering around with react. On my index.tsx section of React, I have a counter on the tab of the web page that counts by 5 and resets at 100. I'm wondering if there is a way to disable the counter and display something like "Rainbow", without deleting the code for the counter.

Basically like an on/off switch that will show "Rainbow when "off" and counter when "on".

Here is the code for the counter:

let counter = 1;
const intervalFunction = () => {
  document.title = "Count is "   counter;
  counter = counter   5;
  if (counter >= 100) {
    counter = 0;
  }

CodePudding user response:

Add a variable switchFlag.

let switchFlag = false; // or true
let counter = 1;
const intervalFunction = () => {
  document.title = switchFlag ? "Count is "   counter : "Rainbow";
  counter = counter   5;
  if (counter >= 100) {
    counter = 0;
  }

CodePudding user response:

try this way :

import React from 'react'
import { useState } from 'react'

const Stack = () => {

    const [swith, setSwitch] = useState(true)
    const [count, setCount] = useState(0)

    const handleCounterIncrease = () => {
        if (count < 100) {
            setCount(count   5)
        }
        else {
            setCount(100)
        }
    }
    const handleCounterDecrease = () => {
        if (count > 5) {
            setCount(count - 5)
        }
        else {
            setCount(0)
        }
    }

    const handleSwitchOff = () => {
        setSwitch(false)
    }
    const handleSwitchOn = () => {
        setSwitch(true)
    }


    return (
        <div>
            {
                swith ?
                    <div>
                        <p>{count}</p>
                        <div style={{ display: "flex" }}>
                            <button onClick={handleCounterIncrease} style={{ backgroundColor: 'green', padding: '3px', marginRight: '20px' }}>Increase </button>
                            <button onClick={handleCounterDecrease} style={{ backgroundColor: 'red', padding: '3px' }}> Decrease</button>
                        </div>
                    </div>
                    : "Rainbow"
            }
            <div style={{ display: "flex", marginTop: '20px' }}>
                <button onClick={handleSwitchOn} style={{ backgroundColor: 'green', padding: '3px', marginRight: '20px' }}>swith on </button>
                <button onClick={handleSwitchOff} style={{ backgroundColor: 'red', padding: '3px' }}>swith off</button>
            </div>

        </div>
    )
}

export default Stack
  • Related