Search code examples
cssreactjsnext.jscomponentsreact-props

How do I pass a property (specifically "theme") to "Components" in a next.js app?


I have a next.js app and this is the _app.tsx file:

import '../styles/globals.css'
import type { AppProps } from 'next/app'
import { createTheme } from '@arwes/design'
import { ThemeProvider, Global, css } from '@emotion/react'
import { globalStyles, blueOnBlack } from '../shared/styles.js'

function MyApp({ Component, pageProps }: AppProps) {
  const theme = createTheme();
  return (
    <ThemeProvider theme={theme}>
      {globalStyles}
      <div style={blueOnBlack(theme)}>
        Futuristic Sci-Fi UI Web Framework
      </div>

      <Component {...pageProps} />
    </ThemeProvider>
  )
}

export default MyApp

The problem is that I need to access theme in index.tsx. So how do I pass this into Component?


Solution

  • I was eventually able to access the parent's theme via emotion's useTheme(). I have to actually build the component outside of the render area of the page's exported function. In the index.tsx file for example:

    function SomeText(props: any) {
      const theme = useTheme()
      return <div style={{ color: theme.palette.primary.dark3 }} {...props} />
    }
    
    
    // Now that above function "SomeText" can be accessed as a component in "Home"
    
    
    const Home: NextPage = () => {
        return (
       ...
        <SomeText className={styles.description}>
          Get started by editing{' '}
          <code className={styles.code}>pages/index.tsx</code>
        </SomeText>
       ...
      )  
    }
    
    export default Home
    

    And that works because the text above is set to "dark3" color.