mercredi 25 septembre 2019

How to build a clicker that counts with click but displays only odd numbers with react components?

So I want to build a clicker as an exercise. The clicker should be build with react components using hooks.

Es every counter it starts at 0 and increases by one. The counter is special in the way that it counts every click but displays only the odd numbers.

Concept: Displayed: 0 1 3 5 7 9 ... Tracked in background: 0 1 2 3 4 5 6 7 8 9 ...

The code that I have so far is a plain counter and I started to implement an if-statement. Not sure though which logic would help me to achieve the clicker.

import React, { useState } from "react";
import ReactDOM from "react-dom";

// Counter that displays only odd numbers, but counts with each click
const App = () => {
  const [count, setCount] = useState(0);

  function onClick() {
    if(count%2!=0) {
      setCount(count + 1)
    } else {
      setCount(count + 1)
    }
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={onClick}>Click me</button>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Aucun commentaire:

Enregistrer un commentaire