Home > Net >  Reactjs If Else for maximum number
Reactjs If Else for maximum number

Time:11-19

Im trying to figure out how to use conditinal rendering in react - if else statements but Im struggling, I need the button, that has only increment, to stop adding number past certain number, lets say 5 and then highlight the number in red.

I have declared function and called it onClick, also declared consts, this is what I have as a base component:

    const [count, setCount] = useState(0);

    function addCount() {
      setCount(prevCount => prevCount   1)
        }

        </div> 
          <h1>Kaufland</h1>
          <p>Customers {count}</p>
          <Uu5Elements.Button  onClick={addCount}> 1</Uu5Elements.Button>
        </div> 

Any help really helps, Im not sure how to add that requirement to the function.

CodePudding user response:

You can try something like:

<div>
  <h1>Kaufland</h1>
  <p style={{ color: count > 5 ? "red" : undefined }}>Customers {count}</p>
  <Uu5Elements.Button
    
    onClick={count > 5 ? undefined : addCount}
  >
     1
  </Uu5Elements.Button>
</div>

CodePudding user response:

You can use && condition to disable the button and change the style of the p tag.

// Get a hook function
const {useState} = React;

const Example = () => {
    const [count, setCount] = useState(0);

  function addCount() {
    setCount((prevCount) => prevCount   1);
  }
  return (
    <div className="App">
      <h1>Kaufland</h1>
          <p style={{color: count>5 && "red"}}>Customers {count}</p>
          <button className="btn2" onClick={addCount} disabled={count>5}> 1</button>
    </div>
  );
};

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <Example title="Example using Hooks:" />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

  • Related