Blog>
Snippets

Next.js 14 Layouts with Styled Components

Illustrate how to use styled components to create reusable styled elements that can be used across different layouts to maintain a consistent look and feel in a Next.js 14 application.
import styled from 'styled-components';

// Styled component for a container
const StyledContainer = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
`;

// Styled component for a header
const StyledHeader = styled.header`
  background: #333;
  color: #fff;
  padding: 10px 0;
`;

// Styled component for a footer
const StyledFooter = styled.footer`
  background: #333;
  color: #fff;
  padding: 10px 0;
`;

export { StyledContainer, StyledHeader, StyledFooter };
This code creates three styled components using styled-components library: a container, a header, and a footer. Each styled component has its own set of CSS properties.
import { StyledHeader, StyledFooter, StyledContainer } from '../components/StyledComponents';

function MyApp({ Component, pageProps }) {
  return (
    <>
      <StyledHeader>
        <nav>
          {/* Navigation content here */}
        </nav>
      </StyledHeader>
      <StyledContainer>
        <Component {...pageProps} />
      </StyledContainer>
      <StyledFooter>
        {/* Footer content here */}
      </StyledFooter>
    </>
  );
}

export default MyApp;
This is the custom `_app.js` file in a Next.js application that uses the styled components for layout. It wraps the page content in a `StyledContainer`, adds a `StyledHeader` at the top, and a `StyledFooter` at the bottom.
import { StyledContainer } from '../components/StyledComponents';

const PageLayout = ({ children }) => (
  <StyledContainer>
    {children}
  </StyledContainer>
);

export default PageLayout;
This code defines a reusable PageLayout component using the StyledContainer component, which can be used to wrap the content of different pages for consistent styling.