M
M
Marat Ivanov2019-07-31 13:11:41
React
Marat Ivanov, 2019-07-31 13:11:41

How to make SPA pages in react?

There is a Header, a side Menu, and a Content field. Made components that accept data in props, such as:

export const Header = props => (
  <div className={`grid-header ${props.wide && "wide"}`}>
    {props.top}
    <div className="grid-header-content">{props.content}</div>
  </div>
);

What should be the project structure? so that the pages in the Content change on the router, the router is in the APP, all three components are loaded into each page accordingly. is it right to do so? How to load props and where should they be stored / and how to load?
With this page construction, the entire application is re-rendered and not just the Content when navigating through the router.
const Home = () => {
  useEffect(() => {
    document.title = "Привет";
  }, []);

  return (
    <Page wide={true}>
      <Header top={<Top />} />
      <SideNav>
        <LeftMenu />
      </SideNav>
      <Content>
        <Overview />
      </Content>
    </Page>
  );
};

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-31
@mrair

Consider moving the shared elements up a level:

const App = () => {
  return (
    <Page wide={true}>
      <Header top={<Top />} />
      <SideNav>
        <LeftMenu />
      </SideNav>
      <Content>
        <Switch>
          <Route path="/" component={Home} />
        </Switch>
      </Content>
    </Page>
  );
};

However, if you are sure that you have chosen the most suitable approach for your project, then the general part can be moved to a separate component:
const PageLayout = ({ wide, top, children }) => {
  return (
    <Page wide={wide}>
      <Header top={top ? top : <Top />} />
      <SideNav>
        <LeftMenu />
      </SideNav>
      <Content>
        {children}
      </Content>
    </Page>
  );
};

Then the page code will be reduced to:
const Home = () => {
  useEffect(() => {
    document.title = "Привет";
  }, []);

  return (
    <PageLayout wide>
      <Overview />
    </PageLayout>
  );
};

To work with head, I advise you to use react-helmet

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question