Categories
React Answers React Projects

How to Create a Countdown Timer with React?

Sometimes, we want to create a countdown timer with React.

In this article, we’ll look at how to create a countdown timer with React.

Create a Countdown Timer with React

We can create a countdown timer by creating a timer component that updates the remaining time regularly.

To do this, we write:

import React, { useEffect, useState } from "react";

const Timer = (props) => {
  const { initialMinute = 0, initialSeconds = 0 } = props;
  const [minutes, setMinutes] = useState(initialMinute);
  const [seconds, setSeconds] = useState(initialSeconds);
  useEffect(() => {
    const myInterval = setInterval(() => {
      if (seconds > 0) {
        setSeconds(seconds - 1);
      }
      if (seconds === 0) {
        if (minutes === 0) {
          clearInterval(myInterval);
        } else {
          setMinutes(minutes - 1);
          setSeconds(59);
        }
      }
    }, 1000);
    return () => {
      clearInterval(myInterval);
    };
  });

  return (
    <div>
      {minutes === 0 && seconds === 0 ? null : (
        <h1>
          {minutes}:{seconds < 10 ? `0${seconds}` : seconds}
        </h1>
      )}
    </div>
  );
};

export default function App() {
  return (
    <>
      <Timer initialMinute={5} initialSeconds={0} />
    </>
  );
}

We create the Timer component that takes the initialMinute and initialSeconds props that sets the initial time.

Then we use the useState prop to create the minutes and seconds state.

Next, we call the useEffect hook with a callback that creates a timer with setInterval .

The timer runs every second.

The setInterval callback checks if the seconds is bigger than 0 and calls setSeconds to decrease the seconds.

If seconds is 0 and minutes is 0, then we call clearInteraval to stop the timer.

Otherwise, we call setMinutes to minutes — 1 and call setSeconds to 59 decrements the minute.

Then we return a callback that calls clearInterval to clear the timer.

Below that, we render the minutes and seconds onto the screen.

If seconds is less than 10 then we add a 0 in front of it.

Conclusion

We can create a countdown timer by creating a timer component that updates the remaining time regularly.

Categories
React Answers

How to Detect Content Changes in contentEditable Elements in React?

Sometimes, we want to detect content changes in a contenteditable element in our React app.

In this article, we’ll look at how to detect content changes in a contenteditable element in our React app.

Detect Content Changes in contentEditable Elements in React

We can detect content changes in contenteditable elements by listening to the input event.

To do this, we write:

import React from "react";

export default function App() {
  return (
    <>
      <div
        contentEditable
        onInput={(e) => console.log(e.currentTarget.textContent)}
      >
        hello world
      </div>
    </>
  );
}

We pass in a function that logs the e.currentTarget.textContent property that has the text content of the div.

It’ll run as we change the content of the div by editing it.

Conclusion

We can detect content changes in contenteditable elements by listening to the input event.

Categories
React Answers

How to Handle the KeyPress Event in React?

Sometimes, we need to do something when a key is pressed in our React app.

In this article, we’ll look at how to do something when a key is pressed in our React app.

Handle the KeyPress Event in React

We can handle the keypress event when a key is pressed in React by setting the onKeyPress prop to an event handler function.

For instance, we can write:

import React from "react";

export default function App() {
  const handleKeyPress = (event) => {
    if (event.key === "Enter") {
      console.log("enter press here! ");
    }
  };
  return (
    <>
      <input type="text" onKeyPress={handleKeyPress} />
    </>
  );
}

We have the handleKeyPress function that takes the event object as a parameter.

The event object has the key property which is set to the string with the key name that’s pressed.

Therefore, we can use it to check if the enter key is pressed by checking aginst the event.key property.

When enter is pressed in the input, the console log will run.

Conclusion

We can handle the keypress event when a key is pressed in React by setting the onKeyPress prop to an event handler function.

Categories
React Answers

How to Conditionally Apply Class Attribute Values with React?

Sometimes, we want to set the class attribute conditionally within our React component.

In this article, we’ll look at how to set the class attribute conditionally within our React component.

Conditionally Apply Class Attribute Values with React

We can set the className prop conditionally to set the class attribute of an element conditionally.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [show, setShow] = useState(false);

  return (
    <>
      <style>
        {`
          .is-shown {
            display: block
          }

          .is-hidden {
            display: none
          }
        `}
      </style>
      <button onClick={() => setShow((s) => !s)}>toggle</button>
      <div className={show ? "is-shown" : "is-hidden"}>hello</div>
    </>
  );
}

We have the styles for the is-shown and is-hidden class in the style element.

Then we have a button that calls setShow to toggle the show state between true and false .

And then we set className to 'is-shown' is show is true and 'is-hidden' otherwise.

Now when we click on the button, we see the div being shown or hidden because we applied the class according to the value of show .

Conclusion

We can set the className prop conditionally to set the class attribute of an element conditionally.

Categories
React Answers

How to Update the Style of a Component on Scroll in React?

Sometimes, we want to update the style of a component on scroll with React.

In this article, we’ll look at how to update the style of a component on scroll with React.

Update the Style of a Component on Scroll in React

We can add a scroll event listener into the useEffect hook callback to listen for the scroll event.

For instance, we can write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [offset, setOffset] = useState(0);

  useEffect(() => {
    window.onscroll = () => {
      setOffset(window.pageYOffset);
    };
  }, []);

  console.log(offset);

  return (
    <div>
      {Array(100)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We have the offset state which we create with the useState hook.

Then we call the useEffect hook with a callback that sets the window.onscroll property to a function that calls setOffset to set the offset to the scroll position.

window.pageYOffset has the vertical scroll position of the browser window.

We then log the offset with console log.

And we render some content that requires scrolling to view in the return statement.

Now when we scroll up or down, we see offset logged from the console log.

Conclusion

We can add a scroll event listener into the useEffect hook callback to listen for the scroll event.