0
export default function PageTemplate() {
  return (
    <div className="layout">
      <LeftMenu />

      <div className="content">

        <TopMenu />

        <div id="other-contents">
          // Contents goes here
        </div>
      </div>
    </div>
  );
}


export default function Index() {
  return (
    <div className="layout">
      <LeftMenu />

      <div className="content">

        <TopMenu />

        <div id="other-contents">
          <h2>I am Index Page<h2/>
        </div>
      </div>
    </div>
  );
}

As you can see most of my contents goes in #other-contents, I will be repeating PageTemplate for every page, I wondering if there is way to just re-use PageTemplate. Instead of repeating code, I would just do something like extends/inherit/whatever possible and reduce the code in Index

I believe this is easier achieved with Class Based Component. But I am wondering if there could function based solution

1 Answer 1

2

React prefers Composition over Inheritance. Use the children prop all react components have.

export default function PageTemplate({ children }) {
  return (
    <div className="layout">
      <LeftMenu />

      <div className="content">

        <TopMenu />

        <div id="other-contents">
          {children}
        </div>
      </div>
    </div>
  );
}

Usage:

<PageTemplate>
  // <-- render any content you want here
</PageTemplate>
Sign up to request clarification or add additional context in comments.

2 Comments

With this if you are to re-write Index, what will it look like?
@Paullo Something like this: <PageTemplate><h2>I am Index Page<h2/></PageTemplate>?

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.