Integrating a CSS-in-JS library with Next.js for Advanced Styling

Present an example of integrating a CSS-in-JS library like emotion for complex styling solutions within Next.js.
import { css, Global, ThemeProvider } from '@emotion/react';

// Define a global style with emotion's Global component
export const globalStyles = (
      body {
        margin: 0;
        padding: 0;
        font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
      /* You can continue to add global styles here */
This piece of code imports necessary emotion components (css, Global, ThemeProvider) and defines global styles that will be applied across all pages in the Next.js application using emotion's Global component.
import { css } from '@emotion/react';

// Create a styled component using emotion's css prop
export const dynamicStyle = ({ color, fontSize }) => css`
  color: ${color};
  font-size: ${fontSize};
Here we define a function `dynamicStyle` that takes a color and fontSize argument and uses the css prop from emotion to create a dynamic style that can be applied to a component.
import { ThemeProvider } from '@emotion/react';

// Define your theme object
const theme = {
  colors: {
    primary: '#ff4757'

// Wrap your application with ThemeProvider and pass the theme object
function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider theme={theme}>
      <Component {...pageProps} />

export default MyApp;
This code wraps the Next.js custom App component with the ThemeProvider component from emotion, passing a theme object. It ensures that the theme and global styles are available throughout the application.
import { css } from '@emotion/react';
import { dynamicStyle } from './styles';

// Usage of dynamicStyle in a functional component
const Button = ({ children, color, fontSize }) => (
  <button css={dynamicStyle({ color, fontSize })}>

export default Button;
Here, we create a styled `Button` component using the `dynamicStyle` function. The `css` prop provided by emotion is used to apply the generated styles dynamically based on the color and fontSize properties.