Home > Mobile >  incorrect navigation icon set via usestate
incorrect navigation icon set via usestate

Time:09-08

creating a dynamic icon with navigation for the header of my application I come across this 'delay', that is, it is always a click late, it even navigates etc but it needs several clicks to work, to better exemplify I will post a gif

the icons are used to navigate between the Home and Editor pages of my app, so using useNavigate

enter image description here

import { useState } from "react";
import { AiOutlineHome, AiOutlineAppstoreAdd } from "react-icons/ai";
import { useNavigate } from "react-router-dom";
import "./style.scss";

export default function Header() {
  const navigate = useNavigate();

  const HomePage = <AiOutlineHome />;
  const EditorPage = <AiOutlineAppstoreAdd />;

  const [home, setHome] = useState(HomePage);

  const handleClick = () => {
    if (home === HomePage) {
      setHome(EditorPage);
      navigate("/");
    } else {
      setHome(HomePage);
      navigate("/editor");
    }
  };

  return (
    <>
      <div className="home">
        <span onClick={handleClick}>{home}</span>
      </div>
    </>
  );
}

CodePudding user response:

Use array to define icons. Try this, it's working on my side:

export default function Header() {
    const navigate = useNavigate();
    const pages = [
        {
            name: "Home",
            icon: <AiOutlineHome />,
        },
        {
            name: "Editor",
            icon: <AiOutlineAppstoreAdd />,
        },
    ];

  const [home, setHome] = useState(pages[0].icon);

  const handleClick = () => {
    if (home.name === "Home") {
        setHome(pages[1]);
      navigate("/");
    }
    else {
        setHome(pages[0]);
      navigate("/editor");
    }
  };

  return (
    <>
      <div className="home">
        <span onClick={handleClick}>{home.icon}</span>
      </div>
    </>
  );
};

CodePudding user response:

Try moving component creation outside of your App component, they are not reactive values

const HomePage = <AiOutlineHome/>;
const EditorPage = <AiOutlineAppstoreAdd/>;

export default function Header() {
    const navigate = useNavigate();


    const [home, setHome] = useState(HomePage); 

    const handleClick = () => {
        if (home === HomePage) {
            setHome(EditorPage);
            navigate("/");
        } else {
            setHome(HomePage);
            navigate("/editor");
        }
    };

    return (
        <>
            <div className="home">
                <span onClick={handleClick}>{home}</span>
            </div>
        </>
    );
}
  • Related