Communication between components in layout

I have a Layout.jsx to define a layout for the whole website. It consists of:

  • Navigation bar (always same content for all pages)
  • Sub Header (changes based on each page)
  • Content (actual content of the page)
  • Aside, Footer, ... for simplicity we ignore these in this example.

On one of the page's Sub Header, (report page sub header) I want to have a <Tab>: "Chart View" and "Table View".

  • When user clicks on Chart, the content of the layout displays <ChartView /> and if clicks on "Table View" the content of the main page displays <TableView />

Layout.jsx

function Layout() {
  // Define all the pages and their routes/content/subheader ...
  const pages = [
    {
      path: '/user',
      content: <UserPage />,
      subheader: <UserSubHeader />
    },
    {
      path: '/report',
      content: <ReportPage />,
      subHeader: <ReportSubHeader />
    }
  ];
  return(
    <>
      <div class="Navbar"><Navbar /></div>
      <Sidebar />
      {pages.map(page => (  // <-------- Loop thought the pages array and render using a Switch and Router.
        <Route path={page.path}>
          <div class="subheader">
            {page.subheader}
          </div>
          <div class="main">
          {page.content}
          </div>
        </Route>
      ))}
    </>
  );
}

ReportSubHeader.jsx

function ReportSubHeader() {
  return(
    <Tabs value={value} onChange={handleChange} >
          <Tab label="Chart View"  />
          <Tab label="Table View"  />
    </Tabs>
  )
}

ReportPage.jsx

function ReportPage() {
  // if first Tab is selected display Chart View,
  // otherwise display TableView
  return (
    <>
    <TabPanel>
      <ChartView />
    </TabPanel>
    <TabPanel>
      <TableView />
    </TabPanel>
  </>);
}

Questions

  1. How to implement this so that the two components can communicate (clicking on ReportSubHeader, causes change in the ReportPage selected tab)?

  2. Is this a good way of defining the layout? (when I might have communication parts in the layout)

Notes

  • One thing I can think of is using Application Context.
  • Apparently Material UI <Tab> and its <TabPanel> cannot be in separate components (as far as I know.) I'm ok to create a custom Tab component for this purpose.


Read more here: https://stackoverflow.com/questions/68462907/communication-between-components-in-layout

Content Attribution

This content was originally published by A-Sharabiani at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: