Introduction
When it comes to styling your React application with a css-in-js approach, styled-components stands out as a top choice. In this post, I'll walk you through how to utilize styled-components in a Next application. By default, Next provides a way to use css-in-js through styled-jsx. However, if you find styled-jsx cumbersome because it requires writing CSS within JSX, which can make your components lengthier, then styled-components might be the right fit for you.
Installation of styled-components
npm install styled-components
// or
yarn add styled-components
Example usage:
import styled from 'styled-components'
const Wrapper = styled.div`
  color: red;
  text-align: center;
`
// Component with input param
const Wrapper2 = styled.div<{$color?: string}>`
  color: ${props => props.$color};
  text-align: center;
`
export default function Index() {
  return (
    <>
      <Wrapper>Demo 1</Wrapper>
      <Wrapper2 $color="green">Demo 2</Wrapper2>
    </>
  )
}
Adding Theme Settings
Here's how to use the ThemeProvider to import a theme for your entire application that can be accessed anywhere, similar to using React context.
import {useContext, useMemo} from 'react'
import styled, {ThemeContext, ThemeProvider} from 'styled-components'
const Wrapper = styled.div`
  color: red;
  text-align: center;
`
const Wrappe2 = (color: string) => styled.div`
  color: ${color};
  text-align: center;
`
const theme = {
  colors: {
    primary: '#0070f3',
  },
}
function Display() {
  const themeContext = useContext(ThemeContext) // get theme context
  console.log('themeContext', themeContext)
  return (
    <>
      <Wrapper>Demo 1</Wrapper>
      <Wrapper2 $color={themeContext?.colors.primary}>Demo 2</Wrapper2>
    </>
  )
}
export default function Index() {
  return (
    <ThemeProvider theme={theme}>
      <Display />
    </ThemeProvider>
  )
}
Using in the Next Application
If you want to use it in a Next application, simply add the following code snippet to the app/layout.tsx file to set up the layout for all pages.
export default function Index({children}: {children: JSX.Element}) {
  return <ThemeProvider theme={theme}>{children}</ThemeProvider>
}
Afterwards, in each page, you can retrieve the theme context as follows:
import {useContext, useMemo} from 'react'
import styled, {ThemeContext, ThemeProvider} from 'styled-components'
export default function Index() {
  const themeContext = useContext(ThemeContext) // get theme context
  return (
    <>
      <Wrapper>Demo 1</Wrapper>
      <Wrapper2 $color={themeContext?.colors.primary}>Demo 2</Wrapper2>
    </>
  )
}
Conclusion
So, we have successfully set up styled-components in React/Next, providing some examples of usage and how to configure using ThemeProvider. Hopefully, this article proves to be helpful.
See more articles here.
 
Comments
Post a Comment