Ask Your Question
4

How can I pass props to the Layout component in NextJs?

asked 2022-06-03 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-04-04 23:00:00 +0000

woof gravatar image

There are different ways you can pass props to the Layout component in NextJs:

  1. Using the props object: You can pass props to the Layout component directly through the props object located in the pages that are using the Layout component.
function HomePage(props) {
  return (
    <Layout pageTitle={props.pageTitle}>
      <h1>Welcome to Next.js!</h1>
    </Layout>
  );
}
  1. Using the getInitialProps() method: You can use the getInitialProps() method to fetch data and pass the data as props to the Layout component.
HomePage.getInitialProps = async function() {
  const data = await getData();
  return {
    pageTitle: data.pageTitle
  };
};

function HomePage(props) {
  return (
    <Layout pageTitle={props.pageTitle}>
      <h1>Welcome to Next.js!</h1>
    </Layout>
  );
}
  1. Using the children property: If you are passing components as children to the Layout component, you can pass props to those children components and access them through the children property.
function HomePage(props) {
  return (
    <Layout>
      <h1>{props.pageTitle}</h1>
      <Paragraph color="blue">This is a paragraph.</Paragraph>
    </Layout>
  );
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-03 11:00:00 +0000

Seen: 19 times

Last updated: Apr 04 '22