Home > database >  How to change react icons while clicking it?
How to change react icons while clicking it?

Time:06-10

I have some icons from react-icons that I want to change from outline to filled whenever I click it but instead of changing itself, it changes all the icons from outline to filled.

Here is my code

function Header() {
  const [isActive, setIsActive] = useState(false);
  return (
    ....
    <div className="flex items-center space-x-6">
      <div className="cursor-pointer select-none">
       {isActive? <AiOutlineHome onClick={()=>{
          setIsActive(!isActive)}}/>:
      <AiFillHome onClick={()=>{
          setIsActive(!isActive)}} />
           }
      </div>

    <div className="cursor-pointer select-none">
      {isActive?<MdOutlineAddBox onClick={()=>{
       setIsActive(!isActive)}}/>:
         <MdAddBox onClick={()=>{
       setIsActive(!isActive)}} />}
     </div>
....
  )}

I know it's because they are sharing the same isActive state, but I don't know exactly how to fix it. Can someone please help me with this?

Edit:

function HeaderIcon({ Icon, ActiveIcon }) {
  const [isActive, setIsActive] = useState(false);
  return (
    <div>{isActive ? <Icon /> : <ActiveIcon />}</div>
  );
}

export default HeaderIcon;

I put this component in a new file but how can I pass the onClick to it?

CodePudding user response:

You need to use two different state

function Header() {
  const [isActive, setIsActive] = useState(false);
  const [isActive2, setIsActive2] = useState(false);
  return (
    ....
    <div className="flex items-center space-x-6">
      <div className="cursor-pointer select-none">
       {isActive? <AiOutlineHome onClick={()=>{
          setIsActive(!isActive)}}/>:
      <AiFillHome onClick={()=>{
          setIsActive(!isActive)}} />
           }
      </div>

    <div className="cursor-pointer select-none">
      {isActive2?<MdOutlineAddBox onClick={()=>{
       setIsActive2(!isActive2)}}/>:
         <MdAddBox onClick={()=>{
       setIsActive2(!isActive2)}} />}
     </div>
....
  )}

I hope this will do magic

CodePudding user response:

The answer for this is:

import React, { useState } from "react";

function HeaderIcon({ inactiveIcon, activeIcon }) {
 const [isActive, setIsActive] = useState(false);

 return (
   <div onClick={() => setIsActive(!isActive)}>
     {isActive ? activeIcon : inactiveIcon}
   </div>
 );
}

export default HeaderIcon;

Then pass in the icon you want.

  • Related