import { useTranslation } from "react-i18next" import styles from…
- User
import { useTranslation } from "react-i18next" import styles from "./build-team.module.css" import { Checkbox } from "../../../ui-component/checkbox/checkbox.component" import { Button } from "../../../ui-component/button/button.component" import { Config } from "../../../utils/config" import { useEffect, useState } from "react" import { TeamKindType } from "../../../types/team-kind.type" import { useAuth } from "../../../ui-component/auth-context/auth-context" import { useModal } from "../../../ui-component/modal" import { UserSignInComponent } from "../../user-sign-in/user-sign-in.component" import { useCookies } from "react-cookie" import { CurrentUserType } from "../../../types/user.type"
// const buildItems = [ // { // image: "../../../public/icons/browser.svg", // title: "Front End Developer", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/product-manager.svg", // title: "Product Manager", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/data-science.svg", // title: "Data Science", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/ux-designer.svg", // title: "UX/UI Designer", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/ai-expert.svg", // title: "AI Expert", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/cloud-engineer.svg", // title: "Cloud Engineer", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/business-metric.svg", // title: "Business Metric", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/backend-developer.svg", // title: "Back End Developer", // width: 40, // height: 40, // }, // ]
export function BuildTeamKind({ selectedKinds, setSelectedKinds, onNext, }: { selectedKinds: TeamKindType[] setSelectedKinds: (kinds: TeamKindType[]) => void onNext: () => void }) { // --------------------------------------------------------------------------- // variables // ---------------------------------------------------------------------------
const modal = useModal() const { t: translate } = useTranslation() const { user } = useAuth()
const [kinds, setKinds] = useState<TeamKindType[]>([]) const [currentUser, setCurrentUser] = useState<CurrentUserType | null>(user) const [cookies] = useCookies(["accessToken", "refreshToken"])
// --------------------------------------------------------------------------- // useeffect // ---------------------------------------------------------------------------
useEffect(() => { getAll() }, [])
useEffect(() => { const currentUser = localStorage.getItem("currentUser") if (!currentUser) return setCurrentUser(JSON.parse(currentUser)) }, [cookies, user])
// --------------------------------------------------------------------------- // functions // ---------------------------------------------------------------------------
function handleItemClick(kind: TeamKindType) { if (selectedKinds.some((selected) => selected.id === kind.id)) { setSelectedKinds( selectedKinds.filter((selected) => selected.id !== kind.id), ) } else { setSelectedKinds([...selectedKinds, kind]) } }
async function getAll() { const response = await fetch(
${Config.url}/api/team/kinds, { method: "GET", headers: { "Content-Type": "application/json", }, credentials: "include", })const result: TeamKindType[] = await response.json() setKinds(result)}
// --------------------------------------------------------------------------- return ( <> {/* --------------------------------------------------------------------------- /} {/ CONTENT /} {/ --------------------------------------------------------------------------- */}
<div className={styles.contentCardWrap}> {kinds .sort((a, b) => a.order - b.order) .map((kind) => ( <div key={kind.id} className={styles.contentCard} onClick={() => handleItemClick(kind)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedKinds.some( (selected) => selected.id === kind.id, )} onClick={() => handleItemClick(kind)} /> <div className={styles.contentSubWrap}> <img src={`${Config.imageUrl + kind.photoUrl}`} width={40} height={40} /> <div className={styles.contentTitle}>{kind.title}</div> </div> </div> ))} </div> {/* --------------------------------------------------------------------------- */} {/* BUTTONS */} {/* --------------------------------------------------------------------------- */} <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={selectedKinds.length === 0} onClick={() => { currentUser && cookies.accessToken && cookies.refreshToken ? onNext() : modal.open({ component: <UserSignInComponent />, width: "80rem", closeOnEsc: true, closeOnOutsideClick: true, modalClassName: styles.modal, }) }} > {translate("button.next")} </Button> </div> </>) } How can I make my fetch to be called only once
- Assistant
To ensure your fetch call is executed only once, you should adjust the dependencies for the
useEffecthook that callsgetAll. Specifically, you'll want to provide an empty dependency array ([]) to prevent the effect from running more than once after the initial render.Here's the updated code with the
useEffecthook configured to execute the fetch request only once:import { useTranslation } from "react-i18next" import styles from "./build-team.module.css" import { Checkbox } from "../../../ui-component/checkbox/checkbox.component" import { Button } from "../../../ui-component/button/button.component" import { Config } from "../../../utils/config" import { useEffect, useState } from "react" import { TeamKindType } from "../../../types/team-kind.type" import { useAuth } from "../../../ui-component/auth-context/auth-context" import { useModal } from "../../../ui-component/modal" import { UserSignInComponent } from "../../user-sign-in/user-sign-in.component" import { useCookies } from "react-cookie" import { CurrentUserType } from "../../../types/user.type" // const buildItems = [ // { // image: "../../../public/icons/browser.svg", // title: "Front End Developer", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/product-manager.svg", // title: "Product Manager", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/data-science.svg", // title: "Data Science", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/ux-designer.svg", // title: "UX/UI Designer", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/ai-expert.svg", // title: "AI Expert", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/cloud-engineer.svg", // title: "Cloud Engineer", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/business-metric.svg", // title: "Business Metric", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/backend-developer.svg", // title: "Back End Developer", // width: 40, // height: 40, // }, // ] export function BuildTeamKind({ selectedKinds, setSelectedKinds, onNext, }: { selectedKinds: TeamKindType[] setSelectedKinds: (kinds: TeamKindType[]) => void onNext: () => void }) { // --------------------------------------------------------------------------- // variables // --------------------------------------------------------------------------- const modal = useModal() const { t: translate } = useTranslation() const { user } = useAuth() const [kinds, setKinds] = useState<TeamKindType[]>([]) const [currentUser, setCurrentUser] = useState<CurrentUserType | null>(user) const [cookies] = useCookies(["accessToken", "refreshToken"]) // --------------------------------------------------------------------------- // useeffect // --------------------------------------------------------------------------- useEffect(() => { getAll() }, []) // Empty dependency array ensures the effect runs only once useEffect(() => { const currentUser = localStorage.getItem("currentUser") if (!currentUser) return setCurrentUser(JSON.parse(currentUser)) }, [cookies, user]) // --------------------------------------------------------------------------- // functions // --------------------------------------------------------------------------- function handleItemClick(kind: TeamKindType) { if (selectedKinds.some((selected) => selected.id === kind.id)) { setSelectedKinds( selectedKinds.filter((selected) => selected.id !== kind.id), ) } else { setSelectedKinds([...selectedKinds, kind]) } } async function getAll() { const response = await fetch(`${Config.url}/api/team/kinds`, { method: "GET", headers: { "Content-Type": "application/json", }, credentials: "include", }) const result: TeamKindType[] = await response.json() setKinds(result) } // --------------------------------------------------------------------------- return ( <> {/* --------------------------------------------------------------------------- */} {/* CONTENT */} {/* --------------------------------------------------------------------------- */} <div className={styles.contentCardWrap}> {kinds .sort((a, b) => a.order - b.order) .map((kind) => ( <div key={kind.id} className={styles.contentCard} onClick={() => handleItemClick(kind)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedKinds.some( (selected) => selected.id === kind.id, )} onClick={() => handleItemClick(kind)} /> <div className={styles.contentSubWrap}> <img src={`${Config.imageUrl + kind.photoUrl}`} width={40} height={40} /> <div className={styles.contentTitle}>{kind.title}</div> </div> </div> ))} </div> {/* --------------------------------------------------------------------------- */} {/* BUTTONS */} {/* --------------------------------------------------------------------------- */} <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={selectedKinds.length === 0} onClick={() => { currentUser && cookies.accessToken && cookies.refreshToken ? onNext() : modal.open({ component: <UserSignInComponent />, width: "80rem", closeOnEsc: true, closeOnOutsideClick: true, modalClassName: styles.modal, }) }} > {translate("button.next")} </Button> </div> </> ) }In the above code, the
useEffectthat calls thegetAllfunction has an empty dependency array, ensuring it's executed only once after the initial render. - User
it’s not executed only once after the initial render. when i change page and come back it re-renders
- Assistant
To prevent
getAllfrom being called every time you navigate back to the component, you can useReact.memoalong with proper key management if component navigation involves re-mounting. Another approach is to cache the fetched data in a higher context or a global state, like Redux or a simple context state, so it doesn’t fetch again unless necessary.Here's one way to implement caching:
- Lift state up: Move the fetch logic and state to a higher-level component or context provider.
- Persist data between renders: Use React context to store the fetched data and share it among components.
Here's how you can implement it with context:
Create Context
First, create a context to store and provide the team kinds data.
// TeamKindsContext.js import React, { createContext, useContext, useEffect, useState } from 'react'; import { Config } from '../../../utils/config'; import { TeamKindType } from '../../../types/team-kind.type'; const TeamKindsContext = createContext([]); export function TeamKindsProvider({ children }) { const [teamKinds, setTeamKinds] = useState<TeamKindType[]>([]); useEffect(() => { async function fetchTeamKinds() { const response = await fetch(`${Config.url}/api/team/kinds`, { method: "GET", headers: { "Content-Type": "application/json", }, credentials: "include", }); const result: TeamKindType[] = await response.json(); setTeamKinds(result); } fetchTeamKinds(); }, []); return ( <TeamKindsContext.Provider value={teamKinds}> {children} </TeamKindsContext.Provider> ); } export function useTeamKinds() { return useContext(TeamKindsContext); }Use Context in Your Component
Wrap your application with the
TeamKindsProviderand useuseTeamKindsin your component.// App.js or a higher-level component import { TeamKindsProvider } from './path/to/TeamKindsContext'; function App() { return ( <TeamKindsProvider> <YourAppComponents /> </TeamKindsProvider> ); }// BuildTeamKind.js import { useTranslation } from "react-i18next"; import styles from "./build-team.module.css"; import { Checkbox } from "../../../ui-component/checkbox/checkbox.component"; import { Button } from "../../../ui-component/button/button.component"; import { useEffect, useState } from "react"; import { TeamKindType } from "../../../types/team-kind.type"; import { useAuth } from "../../../ui-component/auth-context/auth-context"; import { useModal } from "../../../ui-component/modal"; import { UserSignInComponent } from "../../user-sign-in/user-sign-in.component"; import { useCookies } from "react-cookie"; import { CurrentUserType } from "../../../types/user.type"; import { useTeamKinds } from '../../../path/to/TeamKindsContext'; export function BuildTeamKind({ selectedKinds, setSelectedKinds, onNext, }: { selectedKinds: TeamKindType[]; setSelectedKinds: (kinds: TeamKindType[]) => void; onNext: () => void; }) { const modal = useModal(); const { t: translate } = useTranslation(); const { user } = useAuth(); const teamKinds = useTeamKinds(); const [currentUser, setCurrentUser] = useState<CurrentUserType | null>(user); const [cookies] = useCookies(["accessToken", "refreshToken"]); useEffect(() => { const currentUser = localStorage.getItem("currentUser"); if (!currentUser) return; setCurrentUser(JSON.parse(currentUser)); }, [cookies, user]); function handleItemClick(kind: TeamKindType) { if (selectedKinds.some((selected) => selected.id === kind.id)) { setSelectedKinds( selectedKinds.filter((selected) => selected.id !== kind.id), ); } else { setSelectedKinds([...selectedKinds, kind]); } } return ( <> <div className={styles.contentCardWrap}> {teamKinds .sort((a, b) => a.order - b.order) .map((kind) => ( <div key={kind.id} className={styles.contentCard} onClick={() => handleItemClick(kind)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedKinds.some( (selected) => selected.id === kind.id, )} onClick={() => handleItemClick(kind)} /> <div className={styles.contentSubWrap}> <img src={`${Config.imageUrl + kind.photoUrl}`} width={40} height={40} /> <div className={styles.contentTitle}>{kind.title}</div> </div> </div> ))} </div> <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={selectedKinds.length === 0} onClick={() => { currentUser && cookies.accessToken && cookies.refreshToken ? onNext() : modal.open({ component: <UserSignInComponent />, width: "80rem", closeOnEsc: true, closeOnOutsideClick: true, modalClassName: styles.modal, }); }} > {translate("button.next")} </Button> </div> </> ); }By moving data fetching logic to a React context provider, the team kinds data is fetched only once and can be shared across different components, effectively preventing redundant fetches when navigating between pages.
- User
still not effectively prevented redundant fetches when navigating between pages.
- Assistant
To effectively ensure that redundant fetches are prevented entirely when navigating between pages, you can enhance the caching mechanism using a combination of React context and local storage or session storage. This way, the data can persist even if the component is unmounted and remounted.
Step-by-step Solution
- Context with Local Storage: Store fetched data in local storage so it remains available between component unmounts and mounts.
- Check Local Storage First: Before making a fetch request, check if the data already exists in local storage.
Context with Local Storage
Create Context
First, you create a context to store and provide the team kinds data, using local storage to persist the data.
// TeamKindsContext.js import React, { createContext, useContext, useEffect, useState } from 'react'; import { Config } from '../../../utils/config'; import { TeamKindType } from '../../../types/team-kind.type'; const TeamKindsContext = createContext([]); export function TeamKindsProvider({ children }) { const [teamKinds, setTeamKinds] = useState<TeamKindType[]>(() => { const storedKinds = localStorage.getItem('teamKinds'); return storedKinds ? JSON.parse(storedKinds) : []; }); useEffect(() => { async function fetchTeamKinds() { const response = await fetch(`${Config.url}/api/team/kinds`, { method: "GET", headers: { "Content-Type": "application/json", }, credentials: "include", }); const result: TeamKindType[] = await response.json(); setTeamKinds(result); localStorage.setItem('teamKinds', JSON.stringify(result)); } if (teamKinds.length === 0) { fetchTeamKinds(); } }, [teamKinds]); return ( <TeamKindsContext.Provider value={teamKinds}> {children} </TeamKindsContext.Provider> ); } export function useTeamKinds() { return useContext(TeamKindsContext); }Use Context in Your Component
Wrap your application with the
TeamKindsProviderand useuseTeamKindsin your component.// App.js or a higher-level component import { TeamKindsProvider } from './path/to/TeamKindsContext'; function App() { return ( <TeamKindsProvider> <YourAppComponents /> </TeamKindsProvider> ); }// BuildTeamKind.js import { useTranslation } from "react-i18next"; import styles from "./build-team.module.css"; import { Checkbox } from "../../../ui-component/checkbox/checkbox.component"; import { Button } from "../../../ui-component/button/button.component"; import { useEffect, useState } from "react"; import { TeamKindType } from "../../../types/team-kind.type"; import { useAuth } from "../../../ui-component/auth-context/auth-context"; import { useModal } from "../../../ui-component/modal"; import { UserSignInComponent } from "../../user-sign-in/user-sign-in.component"; import { useCookies } from "react-cookie"; import { CurrentUserType } from "../../../types/user.type"; import { useTeamKinds } from '../../../path/to/TeamKindsContext'; export function BuildTeamKind({ selectedKinds, setSelectedKinds, onNext, }: { selectedKinds: TeamKindType[]; setSelectedKinds: (kinds: TeamKindType[]) => void; onNext: () => void; }) { const modal = useModal(); const { t: translate } = useTranslation(); const { user } = useAuth(); const teamKinds = useTeamKinds(); const [currentUser, setCurrentUser] = useState<CurrentUserType | null>(user); const [cookies] = useCookies(["accessToken", "refreshToken"]); useEffect(() => { const currentUser = localStorage.getItem("currentUser"); if (!currentUser) return; setCurrentUser(JSON.parse(currentUser)); }, [cookies, user]); function handleItemClick(kind: TeamKindType) { if (selectedKinds.some((selected) => selected.id === kind.id)) { setSelectedKinds( selectedKinds.filter((selected) => selected.id !== kind.id), ); } else { setSelectedKinds([...selectedKinds, kind]); } } return ( <> <div className={styles.contentCardWrap}> {teamKinds .sort((a, b) => a.order - b.order) .map((kind) => ( <div key={kind.id} className={styles.contentCard} onClick={() => handleItemClick(kind)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedKinds.some( (selected) => selected.id === kind.id, )} onClick={() => handleItemClick(kind)} /> <div className={styles.contentSubWrap}> <img src={`${Config.imageUrl + kind.photoUrl}`} width={40} height={40} /> <div className={styles.contentTitle}>{kind.title}</div> </div> </div> ))} </div> <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={selectedKinds.length === 0} onClick={() => { currentUser && cookies.accessToken && cookies.refreshToken ? onNext() : modal.open({ component: <UserSignInComponent />, width: "80rem", closeOnEsc: true, closeOnOutsideClick: true, modalClassName: styles.modal, }); }} > {translate("button.next")} </Button> </div> </> ); }In this implementation,
teamKindsare initially loaded from local storage. If local storage is empty, it will fetch from the API and save it to local storage, ensuring the data is only fetched once unless the data in local storage is invalidated or cleared. This approach ensures that redundant fetches are prevented when navigating between pages. - User
import { useState } from "react" import { useTranslation } from "react-i18next" import { ToggleButton } from "../../ui-component/toggle-button/toggle-button.component" import { BuildProduct } from "./build-product/build-product.component" import { BuildTeam } from "./build-team/build-team.component"
export function Build() { // --------------------------------------------------------------------------- // variables // ---------------------------------------------------------------------------
const { t } = useTranslation() const [stage, setStage] = useState(0) const [mode, setMode] = useState<"team" | "product">("team")
// --------------------------------------------------------------------------- return ( <> {/* --------------------------------------------------------------------------- /} {/ TOGGLE BUTTON && BUILD TEAM /} {/ --------------------------------------------------------------------------- */}
{stage === 0 && ( <ToggleButton labelOne={t("project.build-team")} labelTwo={t("project.build-project")} onClickLabelOne={() => { setMode("team") }} onClickLabelTwo={() => { setMode("product") }} /> )} {/* --------------------------------------------------------------------------- */} {/* TEAM */} {/* --------------------------------------------------------------------------- */} {mode === "team" && <BuildTeam stage={stage} setStage={setStage} />} {/* --------------------------------------------------------------------------- */} {/* PRODUCT */} {/* --------------------------------------------------------------------------- */} {mode === "product" && <BuildProduct setStage={setStage} stage={stage} />} </>) } import { useEffect, useState } from "react" import { BuildProductTools } from "./build-product-tools.component" import { BuildProductPayment } from "./build-product-payment.component" import styles from "./build-product.module.css" import { BuildTeamMember } from "./build-product-member.component" import { useTranslation } from "react-i18next" import { Icon } from "../../../ui-component/icon/icon.component" import { BuildProductType } from "./build-product-type.component"
export function BuildProduct({ stage, setStage, }: { stage: number setStage: (value: number) => void }) { // --------------------------------------------------------------------------- // variables // ---------------------------------------------------------------------------
const [step, setStep] = useState(1) const [selectedTools, setSelectedTools] = useState<string[]>([]) const [teamSize, setTeamSize] = useState<number | null>(null) const { t } = useTranslation() // --------------------------------------------------------------------------- // functions // ---------------------------------------------------------------------------
useEffect(() => {}, [stage, step])
const handleNextStep = () => { setStep(step + 1) setStage(1) }
const handlePrevStep = () => { if (step === 2) { setStage(0) setStep(step - 1) } else { setStep(step - 1) } }
// --------------------------------------------------------------------------- return ( <> {/* --------------------------------------------------------------------------- /} {/ BACK ICON /} {/ --------------------------------------------------------------------------- */}
{stage === 1 && ( <> {(step === 2 || step === 3 || step === 4) && ( <div className={styles.backIconWrap}> <div className={styles.backIconSubWrap} onClick={handlePrevStep}> <Icon name="fal fa-chevron-left" className={styles.backIcon} size="auto" /> <p className={styles.backIconText}>{t("button.back")}</p> </div> <Icon name="fal fa-xmark" className={styles.xIcon} size="1.6" onClick={() => setStep(1)} /> </div> )} </> )} <div className={styles.contentCardWrap}> {step === 1 && <BuildProductType onNext={handleNextStep} />} {/* --------------------------------------------------------------------------- */} {/* TOOLS */} {/* --------------------------------------------------------------------------- */} {step === 2 && ( <BuildProductTools step={step} selectedTools={selectedTools} setSelectedTools={setSelectedTools} onNext={handleNextStep} /> )} {/* --------------------------------------------------------------------------- */} {/* PAYMENT */} {/* --------------------------------------------------------------------------- */} {step === 3 && ( <BuildProductPayment step={step} teamSize={teamSize} setTeamSize={setTeamSize} onNext={handleNextStep} /> )} {/* --------------------------------------------------------------------------- */} {/* MEMBER */} {/* --------------------------------------------------------------------------- */} {step === 4 && <BuildTeamMember />} </div> </>) } when I am in build product page stage === 2 then I click back icon, it navigates me to build component but togglebutton active color on build team. I want when I click back button on product component it should navigates to build component and active color should be on build product. How to do it ?
- Assistant
To achieve the desired functionality where the active color of the
ToggleButtonreflects the correct mode (teamorproduct) when navigating back from theBuildProductcomponent to theBuildcomponent, you need to ensure that themodestate is correctly managed between the components.Here is a refined approach to ensure that the
modestate is preserved and the correct toggle button is active:- Pass the
modeState as Props: Pass themodestate and its updater function fromBuildtoBuildProduct. - Update the
modeState: When navigating back, update themodestate if needed.
Updated
BuildComponentimport { useState } from "react" import { useTranslation } from "react-i18next" import { ToggleButton } from "../../ui-component/toggle-button/toggle-button.component" import { BuildProduct } from "./build-product/build-product.component" import { BuildTeam } from "./build-team/build-team.component" export function Build() { const { t } = useTranslation() const [stage, setStage] = useState(0) const [mode, setMode] = useState<"team" | "product">("team") return ( <> {stage === 0 && ( <ToggleButton labelOne={t("project.build-team")} labelTwo={t("project.build-project")} onClickLabelOne={() => { setMode("team") }} onClickLabelTwo={() => { setMode("product") }} /> )} {mode === "team" && <BuildTeam stage={stage} setStage={setStage} setMode={setMode} />} {mode === "product" && <BuildProduct setStage={setStage} stage={stage} setMode={setMode} />} </> ) }Updated
BuildProductComponentIn
BuildProduct, update thehandlePrevStepfunction to set the mode to"product"when navigating back to ensure the toggle button state is correctly maintained.import { useEffect, useState } from "react" import { BuildProductTools } from "./build-product-tools.component" import { BuildProductPayment } from "./build-product-payment.component" import styles from "./build-product.module.css" import { BuildTeamMember } from "./build-product-member.component" import { useTranslation } from "react-i18next" import { Icon } from "../../../ui-component/icon/icon.component" import { BuildProductType } from "./build-product-type.component" export function BuildProduct({ stage, setStage, setMode // Add setMode prop }: { stage: number setStage: (value: number) => void setMode: (value: "team" | "product") => void // Add setMode type }) { const [step, setStep] = useState(1) const [selectedTools, setSelectedTools] = useState<string[]>([]) const [teamSize, setTeamSize] = useState<number | null>(null) const { t } = useTranslation() useEffect(() => {}, [stage, step]) const handleNextStep = () => { setStep(step + 1) setStage(1) } const handlePrevStep = () => { if (step === 2) { setStage(0) setStep(step - 1) setMode("product") // Ensure mode is set to "product" } else { setStep(step - 1) } } return ( <> {stage === 1 && ( <> {(step === 2 || step === 3 || step === 4) && ( <div className={styles.backIconWrap}> <div className={styles.backIconSubWrap} onClick={handlePrevStep}> <Icon name="fal fa-chevron-left" className={styles.backIcon} size="auto" /> <p className={styles.backIconText}>{t("button.back")}</p> </div> <Icon name="fal fa-xmark" className={styles.xIcon} size="1.6" onClick={() => setStep(1)} /> </div> )} </> )} <div className={styles.contentCardWrap}> {step === 1 && <BuildProductType onNext={handleNextStep} />} {step === 2 && ( <BuildProductTools step={step} selectedTools={selectedTools} setSelectedTools={setSelectedTools} onNext={handleNextStep} /> )} {step === 3 && ( <BuildProductPayment step={step} teamSize={teamSize} setTeamSize={setTeamSize} onNext={handleNextStep} /> )} {step === 4 && <BuildTeamMember />} </div> </> ) }By ensuring the
modeis updated correctly when navigating back, theToggleButtonwill reflect the correct active state. ThesetMode("product")line in thehandlePrevStepfunction reinvokes the active state on theBuildcomponent when coming back from theBuildProductview. - Pass the
- User
import styles from "./toggle-button.module.css"
export function ToggleButton({ labelOne, labelTwo, onClickLabelOne, onClickLabelTwo, }: { labelOne: string labelTwo: string onClickLabelOne: () => void onClickLabelTwo: () => void }) { return ( {labelOne} {labelTwo} ) } .toggleWrapper { display: inline-block; }
.toggleContainer { position: relative; display: grid; grid-template-columns: repeat(2, 1fr); width: fit-content; border: 1px solid #b5b8bf; border-radius: 10rem; background: #f6f2fa; font-size: 1.7rem; font-weight: 700; color: #414044; cursor: pointer; }
.toggleContainer::before { content: ""; position: absolute; width: 50%; height: 100%; left: 0%; border-radius: 10rem; background: #4759fc; transition: all 0.3s; }
.toggleCheckbox:checked + .toggleContainer::before { left: 50%; }
.toggleContainer div { padding: 1.5rem 2rem; text-align: center; z-index: 1; }
.toggleCheckbox { display: none; }
.toggleCheckbox:checked + .toggleContainer div:first-child { color: #414044; transition: color 0.3s; }
.toggleCheckbox:checked + .toggleContainer div:last-child { color: #fff; transition: color 0.3s; }
.toggleCheckbox + .toggleContainer div:first-child { color: white; transition: color 0.3s; }
.toggleCheckbox + .toggleContainer div:last-child { color: #414044; transition: color 0.3s; }
@media (max-width: 600px) { .toggleContainer { width: 100%; font-size: 1.5rem; }
.toggleWrapper { width: 100%; display: flex; justify-content: center; } .toggleContainer div { padding: 1rem 1.5rem; } } I think the issue on toggle button. Espacially here .toggleContainer::before.
- Assistant
Thank you for providing the CSS and the component code. From your description and the provided code, it seems that the current implementation of the
ToggleButtoncomponent does not actively track or persist the selected state (labelOnevs.labelTwo). Instead, it relies on the state of the input checkbox, which may not reflect changes accurately when navigating back and forth.Enhancing the Toggle Button
To fix this, we need to ensure that the
ToggleButtoncomponent can accept and reflect the current active mode. We can do this by adding a controlled input state to theToggleButtoncomponent, which updates based on clicks from parent component props.Here's a refined approach:
- Pass Active State as Props: The
ToggleButtonshould accept an active state to determine which label is currently active. - Update State on Click: Update the active state in the parent component on button-click events.
Updated
ToggleButtonComponentimport styles from "./toggle-button.module.css" export function ToggleButton({ labelOne, labelTwo, onClickLabelOne, onClickLabelTwo, activeLabel, }: { labelOne: string labelTwo: string onClickLabelOne: () => void onClickLabelTwo: () => void activeLabel: "labelOne" | "labelTwo" }) { return ( <div className={styles.toggleWrapper}> <div className={styles.toggleContainer} data-active={activeLabel}> <div onClick={onClickLabelOne}>{labelOne}</div> <div onClick={onClickLabelTwo}>{labelTwo}</div> </div> </div> ) }Updated CSS
You can use a data attribute (
data-active) to control the visual state of the toggle..toggleWrapper { display: inline-block; } .toggleContainer { position: relative; display: grid; grid-template-columns: repeat(2, 1fr); width: fit-content; border: 1px solid #b5b8bf; border-radius: 10rem; background: #f6f2fa; font-size: 1.7rem; font-weight: 700; color: #414044; cursor: pointer; } .toggleContainer::before { content: ""; position: absolute; width: 50%; height: 100%; left: 0%; border-radius: 10rem; background: #4759fc; transition: all 0.3s; } /* Data Attribute Selector for Active State */ .toggleContainer[data-active="labelTwo"]::before { left: 50%; } .toggleContainer div { padding: 1.5rem 2rem; text-align: center; z-index: 1; } .toggleContainer[data-active="labelOne"] div:first-child { color: white; } .toggleContainer[data-active="labelTwo"] div:last-child { color: white; } @media (max-width: 600px) { .toggleContainer { width: 100%; font-size: 1.5rem; } .toggleWrapper { width: 100%; display: flex; justify-content: center; } .toggleContainer div { padding: 1rem 1.5rem; } }Updated
BuildComponentNow, let's pass the
activeLabeldown to theToggleButtonfrom theBuildcomponent.import { useState } from "react" import { useTranslation } from "react-i18next" import { ToggleButton } from "../../ui-component/toggle-button/toggle-button.component" import { BuildProduct } from "./build-product/build-product.component" import { BuildTeam } from "./build-team/build-team.component" export function Build() { const { t } = useTranslation() const [stage, setStage] = useState(0) const [mode, setMode] = useState<"team" | "product">("team") return ( <> {stage === 0 && ( <ToggleButton labelOne={t("project.build-team")} labelTwo={t("project.build-project")} onClickLabelOne={() => { setMode("team") }} onClickLabelTwo={() => { setMode("product") }} activeLabel={mode === "team" ? "labelOne" : "labelTwo"} // Active state /> )} {mode === "team" && <BuildTeam stage={stage} setStage={setStage} setMode={setMode} />} {mode === "product" && <BuildProduct setStage={setStage} stage={stage} setMode={setMode} />} </> ) }Updated
BuildProductComponentIn
BuildProduct, update thehandlePrevStepfunction to ensure themodestate is correctly preserved.import { useEffect, useState } from "react" import { BuildProductTools } from "./build-product-tools.component" import { BuildProductPayment } from "./build-product-payment.component" import styles from "./build-product.module.css" import { BuildTeamMember } from "./build-product-member.component" import { useTranslation } from "react-i18next" import { Icon } from "../../../ui-component/icon/icon.component" import { BuildProductType } from "./build-product-type.component" export function BuildProduct({ stage, setStage, setMode // Add setMode prop }: { stage: number setStage: (value: number) => void setMode: (value: "team" | "product") => void // Add setMode type }) { const [step, setStep] = useState(1) const [selectedTools, setSelectedTools] = useState<string[]>([]) const [teamSize, setTeamSize] = useState<number | null>(null) const { t } = useTranslation() useEffect(() => {}, [stage, step]) const handleNextStep = () => { setStep(step + 1) setStage(1) } const handlePrevStep = () => { if (step === 2) { setStage(0) setStep(step - 1) setMode("product") // Ensure mode is set to "product" } else { setStep(step - 1) } } return ( <> {stage === 1 && ( <> {(step === 2 || step === 3 || step === 4) && ( <div className={styles.backIconWrap}> <div className={styles.backIconSubWrap} onClick={handlePrevStep}> <Icon name="fal fa-chevron-left" className={styles.backIcon} size="auto" /> <p className={styles.backIconText}>{t("button.back")}</p> </div> <Icon name="fal fa-xmark" className={styles.xIcon} size="1.6" onClick={() => setStep(1)} /> </div> )} </> )} <div className={styles.contentCardWrap}> {step === 1 && <BuildProductType onNext={handleNextStep} />} {step === 2 && ( <BuildProductTools step={step} selectedTools={selectedTools} setSelectedTools={setSelectedTools} onNext={handleNextStep} /> )} {step === 3 && ( <BuildProductPayment step={step} teamSize={teamSize} setTeamSize={setTeamSize} onNext={handleNextStep} /> )} {step === 4 && <BuildTeamMember />} </div> </> ) }By passing the
activeLabelprop all the way down and using it in yourToggleButtoncomponent, you ensure that the correct toggle state is displayed even after navigating back and forth. - Pass Active State as Props: The