Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i setState for color change

I already have the condition, but i need to set the state, if i setColor on the if method, give me error- Too many re-renders. React limits the number of renders to prevent an infinite loop.

State:

const [color, setColor] = useState();

Map:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {data.map((doc) => {
    let verificacao = "";

    if (doc.status === "Não Necessário") {
      verificacao = "Proxima Verificação:";
      setColor(true)

    } else if (doc.status === "Verificado e Conforme") {
      verificacao = "Data:";
      setColor(false)

    } else {
      console.log("ERRO");
    }

    return (

The span i want to change the color:

   <div className="row">
                <div className="pontos">
                  <span className={color ? "red" : "green"}>
                    {doc.status}
                  </span>
                  <span className="data-status">{verificacao}</span>
                  {JSON.stringify(
                    doc.dateVerificado
                      .toDate()
                      .toISOString()
                      .replace(/T.*/, "")
                      .split("-")
                      .reverse()
                      .join("-")
                  )}
                </div>
              </div>

Full Code:

import React, { useEffect, useState } from "react";
import { Button } from "react-bootstrap";
import ManutencaoDataService from 
"../../Services/ManutecaoDataService";
import "./ManutencaoInfo.css";

const ManutencaoInfo = ({ getDataId }) => {
const [data, setData] = useState([]);
const [color, setColor] = useState();

 useEffect(() => {

  getData();
  return () => {
   setData([]);
 };
}, []);

const getData = async () => {
  const data = await ManutencaoDataService.getAllData();
  console.log(data.docs);
  setData(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};

const deleteHandler = async (id) => {
  await ManutencaoDataService.deleteData(id);
  getData();
 };


return (
<>
  <div className=" container mb-2">
    <Button variant="dark edit" onClick={getData}>
      Atualizar Lista
    </Button>
  </div>

  {/* <pre>{JSON.stringify(books, undefined, 2)}</pre>} */}

  {data.map((doc) => {
    let verificacao = "";

    if (doc.status === "Não Necessário") {
      verificacao = "Proxima Verificação:";
      setColor(true)
     
    } else if (doc.status === "Verificado e Conforme") {
      verificacao = "Data:";
      setColor(false)
     
    } else {
      console.log("ERRO");
    }

    return (
      <div key={doc.id} className="container-principal">
        <div className="container">
          <div className="row relatorio">
            <div className="col">
              <div className="departamento">
                <h3>{doc.departamentos}</h3>
              </div>
            </div>
          </div>
          <div className="row detalhes">
            <div className="col">
              <div className="row">
                <div className="pontos">
                  <span className="identificacao">Equipamento: 
                </span>
                  {doc.equipamentos}
                </div>
              </div>
              <div className="row">
                <div className="pontos">
                  <span className="identificacao">Responsável: 
               </span>
                  {doc.responsaveis}
                </div>
              </div>
              <div className="row">
                <div className="pontos">
                  <span className="codigo">{doc.codigos.codigo} 
                </span>
                  <span className="tipo">{doc.tipo}</span>
                </div>
              </div>
            </div>
            <div className="col ">
              <div className="row">
                <div className="pontos">
                  <span className="identificacao">Data Manutenção: 
                </span>
                  {JSON.stringify(
                    doc.dateManutencao
                      .toDate()
                      .toISOString()
                      .replace(/T.*/, "")
                      .split("-")
                      .reverse()
                      .join("-")
                  )}
                </div>
              </div>
              <div className="row">
                <div className="pontos">
                  <span className={color ? "red" : "green"}>
                    {doc.status}
                  </span>
                  <span className="data-status">{verificacao}</span>
                  {JSON.stringify(
                    doc.dateVerificado
                      .toDate()
                      .toISOString()
                      .replace(/T.*/, "")
                      .split("-")
                      .reverse()
                      .join("-")
                  )}
                </div>
              </div>
              <div className="row">
                <div className="pontos">{doc.codigos.observacoes} 
               </div>
              </div>
            </div>
          </div>
          <div className="row botoes">
            <div className="col">
              <span className="botao-editar">
                <Button
                  variant="secondary"
                  className="edit"
                  onClick={(e) => getDataId(doc.id)}
                >
                  Editar
                </Button>
              </span>
              <span className="botao-apagar">
                <Button
                  variant="danger"
                  className="delete"
                  onClick={(e) => deleteHandler(doc.id)}
                >
                  Apagar
                </Button>
              </span>
            </div>
          </div>
        </div>
      </div>
    );
  })}
</>
  );
 };

  export default ManutencaoInfo;

>Solution :

Instead of using state, I would recommend using doc’s status property for using the correct CSS class like this:

    <span className={doc.status === "Não Necessário" ? "red" : "green"}>
        {doc.status}
    </span>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading