0

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.

1
  • You shouldn't store React component inside state. Why don't you use a string to determine the color, for example? Commented Jun 12, 2022 at 14:47

2 Answers 2

1

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 />
        </>
    );
};
Sign up to request clarification or add additional context in comments.

Comments

1
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} />

1 Comment

Plus use react-router if you want the "profile page" in separate page and still use the same layout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.