Home > Software engineering >  onClick in React changes all of the classes states in react
onClick in React changes all of the classes states in react

Time:01-14

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;

plese help me for fixed bug thanks plese help me for fixed bug thanksplese help me for fixed bug thanksplese help me for fixed bug thanksplese help me for fixed bug thanksplese help me for fixed bug thanksplese help me for fixed bug thanksplese help me for fixed bug thanksplese help me for fixed bug thanksplese help me for fixed bug thanks

image the styles here

CodePudding user response:

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;

  •  Tags:  
  • Related