Using hooks inside createGlobalStyle

Viewed 35

Hey I am trying to use hooks inside styled-components - createGlobalStyle. I know that this is not possible, because createGlobalStyle is a function and neither a component nor a custom hook. Maybe someone knows a workaround or a solution :).

export const GlobalStyle = createGlobalStyle`
 p {
   padding: ${p => useMediaQuery('min-width(768px)') && 12px};
 }    
`
2 Answers

One workaround can be to add a media query hook anywhere in your code, catch the screen size, send value in props (prop drilling, context Api, redux) to make your styled components adapt to your screen.

You may go through this link

You are not need to use hooks outside of functional components. Poof

Two ways, which i see, how you can do your task.

  1. add media query directly in createGlobalStyle.

    export const GlobalStyle = createGlobalStyle`
    @media only screen and (min-width: 768px) {
      p {
        padding: 12px;
      }  
    }
    `
    
  2. make separate function with some logic

    const minWidthMedia = (minWidth: string) => {
      const size = getScreenSize()
      const isValid = minWidth > size.width
      if (!isValid) return
    
      return css`
        p {
            padding: 12px;
          }
      `
      // or 
      // without validation logic
      // return css`
      // @media only screen and (min-width: ${minWidth}px) {
      //   p {
      //     padding: 12px;
      //   }
      // }
    }
    
    export const GlobalStyle = createGlobalStyle`
      ${minWidthMedia('768px')}   
    `
    
Related