A
A
Alexander Zharchenko2021-10-16 19:14:44
React
Alexander Zharchenko, 2021-10-16 19:14:44

How to re-render a functional component after changing the route?

There is a code like this:

const ContenWrapper: FC<ElementsIds> = memo(({ ids }) => {
  const DashboardContent = () => (
    <>
      <TitleStyled id={ids.content.contentTitleId}>
        {messages.title.default}
      </TitleStyled>
      <DescriptionStyled id={ids.content.contentDesctiptionId}>
        {messages.description.default}
      </DescriptionStyled>
    </>
  );

  const GameContent = () => <TitleStyled>{"блаблабла"}</TitleStyled>;

  return (
    <ContentWrapperStyled id={ids.content.contentWrapperId}>
      <ScrollWrapperStyled id={ids.content.contentScrollWrapperId}>
        <Route path="/" render={DashboardContent} />
        <Route path="/game" render={GameContent} />
      </ScrollWrapperStyled>
    </ContentWrapperStyled>
  );
});


In another component, when the button is clicked, the route changes.
In this case, depending on the route, what is specified in render is simply drawn .

How to make it so that when the route changes, the ContenWrapper itself is redrawn ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Dvoryanov, 2021-10-16
@exxxcitation1

You can use the useLocation() router hook.
The idea is this - we pull the hook, wrap the right place, which should be rendered in useMemo with a dependency on the router hook
. For example -

// импортируем хук useMemo
import { useMemo } from "react";
// импортируем хук useLocation
import { useLocation } from "react-router-dom";

const ContenWrapper: FC<ElementsIds> = memo(({ ids }) => {
  // Добавляем хук перемещений
  const { pathname } = useLocation();

  // Если нужен например этот компонент, чтоб ререндерились изменения, оборачиваем в хук useMemo
  const DashboardContent = useMemo(
    () => (
      <>
        <TitleStyled id={ids.content.contentTitleId}>
          {messages.title.default}
        </TitleStyled>
        <DescriptionStyled id={ids.content.contentDesctiptionId}>
          {messages.description.default}
        </DescriptionStyled>
      </>
    ), 
    [pathname] // Зависимость, при изменении которой произойдет ререндер
  );

  const GameContent = () => <TitleStyled>{"блаблабла"}</TitleStyled>;

  return (
    <ContentWrapperStyled id={ids.content.contentWrapperId}>
      <ScrollWrapperStyled id={ids.content.contentScrollWrapperId}>
        <Route path="/" render={DashboardContent} />
        <Route path="/game" render={GameContent} />
      </ScrollWrapperStyled>
    </ContentWrapperStyled>
  );
});

It’s just not clear why if one component goes to one route, and the other to another, but they don’t work in the background

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question