Home > OS >  Big React component with conditional rendering or smaller separate components?
Big React component with conditional rendering or smaller separate components?

Time:09-13

I have a specific question about coding practices for React.js.

I have two pages in my React application that render UI cards based on data returned from the backend. They are almost identical, except one has a UI for filter options and another has a search bar.

What would be the better way of structuring these two different pages and why?

----------------

OPTION A (one big component with conditional rendering)

App.jsx

<Router>
  <Routes>
    <Route path="/page1" element={<Page showFilter=true showSearchBar=false />} />
    <Route path="/page2" element={<Page showFilter=false showSearchBar=true />} />
  </Routes>
</Router>

Page.jsx

function Page(props) {
  return (
    <>
      <Header />
      {props.showSearchBar && (<SearchBar />)}
      {props.showFilter && (<Filter />)}
      <ItemsList />
      <Footer />
    </>
  )
}

----------------

OPTION B (two separate components with sub-component reuse)

App.jsx

<Router>
  <Routes>
    <Route path="/page1" element={<Page1 />} />
    <Route path="/page2" element={<Page2 />} />
  </Routes>
</Router>

Page1.jsx

function Page1(props) {
  return (
    <>
      <Header />
      <Filter />
      <ItemsList />
      <Footer />
    </>
  )
}

Page2.jsx

function Page2(props) {
  return (
    <>
      <Header />
      <SearchBar />
      <ItemsList />
      <Footer />
    </>
  )
}

----------------

Of course the above list of options isn't exhaustive. If there are any other ways to solve this that might be more suitable for my task, I'd be happy to hear it.

Thanks!

CodePudding user response:

Option C React Composition

App.jsx

<Router>
  <Routes>
    <Route path="/page1" element={<Page><Filter /></Page>} />
    <Route path="/page2" element={<Page><SearchBar /></Page>} />
  </Routes>
</Router>

Page.jsx

function Page(props) {
  return (
    <>
      <Header />
      {props.children}
      <ItemsList />
      <Footer />
    </>
  )
}

CodePudding user response:

I think option A seems fine also, at least until the UI start to differ significantly then you might have to go for option B.

  • Related