Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
onClick in React changes all of the classes states in react

I have creates a aside in react and I want to change their state to active when clicked on each of them, but when I click on any item all of them suddenly get activated. How to fix this?

import React, { useState, useEffect } from "react";
import { Col, Image, Row } from "react-bootstrap";
import "./Company.scss";

// * api
import { getCoin } from "../services/api";

// *spinner
import Loader from "./Loader";

const Company = () => {
  const [changeClass, setChangeClass] = useState(false);
  const [coins, setCoins] = useState([]);

  useEffect(() => {
    const fetchAPI = async () => {
      const data = await getCoin();
      setCoins(data);
    };
    fetchAPI();
  }, []);

  const myHandler = () => {
    setChangeClass(true);
    console.log("trued");
  };

  const myHandler2 = () => {
    console.log();
  };

  return (
    <>
      {coins.length ? (
        coins.map((coin) => (
          <Row
            className={
              changeClass
                ? "p-2 border-top d-flex align-items-center company-list-single-active"
                : "p-2 border-top d-flex align-items-center company-list-single"
            }
            onClick={() => {
              myHandler();
              myHandler2();
            }}
            key={coin.id}
          >
            <Col xxl="2" xl="2" lg="2" md="2" sm="2" xs="2">
              <Image
                src={coin.image}
                alt={coin.name}
                className="coin-image mx-2"
                fluid
              />
            </Col>
            <Col>
              <span>{coin.name}</span>
            </Col>
          </Row>
        ))
      ) : (
        <Loader />
      )}
    </>
  );
};
export default Company;

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you use a test to display selected coin by the same state and it is toggled between true or false. I added a state to save the selected coin and test on it on looping. On the onClick we can directly update the selected item.

you cannot do that "coins.length ?" this will be always true if type of coins is array i added a test like "coins.length > 0 ?" here the solution

import React, { useState, useEffect } from 'react';
import { Col, Image, Row } from 'react-bootstrap';
import './Company.scss';

// * api
import { getCoin } from '../services/api';

// *spinner
import Loader from './Loader';

const Company = () => {
  const [selectedCoin, setSelectedCoin] = useState(null);
  const [coins, setCoins] = useState([]);

  useEffect(() => {
    const fetchAPI = async () => {
      const data = await getCoin();
      setCoins(data);
    };
    fetchAPI();
  }, []);

  return (
    <>
      {coins.length > 0 ? (
        coins.map((coin) => (
          <Row
            className={
              selectedCoin === coin.id
                ? 'p-2 border-top d-flex align-items-center company-list-single-active'
                : 'p-2 border-top d-flex align-items-center company-list-single'
            }
            onClick={() => setSelectedCoin(coin.id)}
            key={coin.id}
          >
            <Col xxl="2" xl="2" lg="2" md="2" sm="2" xs="2">
              <Image src={coin.image} alt={coin.name} className="coin-image mx-2" fluid />
            </Col>
            <Col>
              <span>{coin.name}</span>
            </Col>
          </Row>
        ))
      ) : (
        <Loader />
      )}
    </>
  );
};
export default Company;

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda