In one page i wanna render two components at the same time. I have a bottom navbar that when i click on let's say profile icon, it will render the profile page. But i wanna change the color of the icon based in what component is being rendered. If i was using react router i could just check the current location, but in this case i'm in the same page and just changing one of the components, the only way i could think of changing the color dynamically is by getting the component's name. But i don't know how to do it with typescript.
I have this state:
const [page, setPage] = useState<React.ReactNode>(<UserChats />);
And i tried get the component's name by page.type.name
, but it says that:
Property 'type' does not exist on type 'string | number | boolean | ReactElement<any, string | JSXElementConstructor> | ReactFragment | ReactPortal'.
How can i get the component's name? Or, if there's a better way i'm all ears.
CodePudding user response:
Can you please try something like that?
const PAGE_STATE = {
USER_CHAT: 'USER_CHAT',
OTHER: 'OTHER'
};
const YourComponent = () => {
const [pageState, setPageState] = useState(PAGE_STATE.USER_CHAT);
return (
<>
{pageState === PAGE_STATE.USER_CHAT && <UserChat />}
{pageState === PAGE_STATE.OTHER && <Other />
</>
);
};
CodePudding user response:
import React, { useState } from 'react'
// Store Components into enum
enum PageState {
Chat = ChatPage,
Other = OtherPage
}
const StatedPage = () => {
const [state, setState] = useState<PageState>(PageState.Chat); // can only set state as a member of PageState
return (
<>
{state} // Render PageState's member value
</>
);
};
interface PageProps{
state: PageState
}
const Page = (props: PageProps) => {
return (
<>
{props.state}
</>
);
};
// Pass PageState member
<Page state={PageState.Chat} />