Last active
January 14, 2022 15:27
-
-
Save rickyalmeidadev/ef26bb6524990c81b9b98e19abc5109d to your computer and use it in GitHub Desktop.
Example of using attrs method from styled
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getPrefersColorScheme = () => { | |
if ('matchMedia' in window) { | |
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches; | |
return isDark ? 'dark' : 'light'; | |
} | |
return 'light'; | |
}; | |
export default getPrefersColorScheme; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react'; | |
import { Logo } from './styles'; | |
import getPrefersColorScheme from './get-prefers-color-scheme' | |
const Example = () => { | |
const [mode, setMode] = useState(getPrefersColorScheme()); | |
const toggle = () => { | |
setMode(prevMode => prevMode === 'light' ? 'dark' : 'light'); | |
}; | |
return ( | |
<div> | |
<Logo mode={mode} /> | |
<button onClick={toggle}>Toggle</button> | |
</div> | |
); | |
}; | |
export default Example; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import styled from 'styled-components'; | |
import { DarkLogo, LightLogo } from 'path-to-logos'; | |
const logos = { | |
dark: DarkLogo, | |
light: LightLogo, | |
}; | |
export const Logo = styled.img.attrs(({ mode = 'light' }) => ({ | |
src: logos[mode], | |
alt: 'Logo', | |
}))` | |
/* ... */ | |
`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment