D
D
Dmitry Vorobyov2021-05-23 09:47:59
React
Dmitry Vorobyov, 2021-05-23 09:47:59

How to stop setInterval in react when navigating between pages using NavLink?

React application, the setInterval function works on the page.

import React from "react";
import logo from "./logo/logo.svg";
import style from "./StartPage.module.css";
import Cell from "./Cell";
import { NavLink } from "react-router-dom";

export const change = (arr) => {
  let i = -1;
  setInterval(function () {
    document.querySelector("i").className =
      arr[(i = ++i == arr.length ? 0 : i)];
  }, 1000);
};

const StartPage = () => {
  const arrD = [style.indicator, style.indicatorleft];
  change(arrD);
  return (
    <div className={style.grid}>
      <img src={logo} alt="bugaga"></img>

      <div className={style.radiobutton}>
        <NavLink
          onClick={() => {
            clearInterval(change);
          }}
          to="/radio">
          RadioButton
        </NavLink>
        <div className={style.list}>
          <div className={style.cell}>
            <div className={style.togle}>
              <i className={style.indicatorleft}></i>
            </div>
          </div>
          <Cell />
          <Cell />
          <Cell />
          <Cell />
          <Cell />
          <Cell />
          <Cell />
          <Cell />
        </div>
      </div>
      <div className={style.radio}>
        <NavLink to="/button">Button</NavLink>
        <div className={style.list}></div>
      </div>
    </div>
  );
};

export default StartPage;


But when going to another page through NavLink

<div className={style.radiobutton}>
        <NavLink
          onClick={() => {
            clearInterval(change);
          }}
          to="/radio">
          RadioButton
        </NavLink>


Gives an error message. 60a9fa75dc14d473987541.png
Tell me how to fix it or another correct way to stop setInterval when NavLink fires.
If you need code for other components, write

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kentavr16, 2021-05-23
@Kentavr16

document.querySelector("i").className =
      arr[(i = ++i == arr.length ? 0 : i)];

the error occurs because you are trying to set the className as an array.
the correct entry is className = "myClass" or something similar. What would you like to do with this code? just disable the timer?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question