Skip to content

Instantly share code, notes, and snippets.

@yaboynoem
Created July 6, 2022 23:07
Show Gist options
  • Save yaboynoem/13689cb6a625b8625e88e4a78648868f to your computer and use it in GitHub Desktop.
Save yaboynoem/13689cb6a625b8625e88e4a78648868f to your computer and use it in GitHub Desktop.
Theme changer with react and framer motion
import styled from "styled-components"
export const ThemeChangerStyle = styled.div`
align-items: center;
border-radius: 5px;
cursor: pointer;
display: flex;
height: 40px;
justify-contents: center;
opacity: 1;
overflow: hidden;
width: 40px;
`
import React, { ReactElement } from "react"
import { motion } from "framer-motion"
import { useSelector } from "react-redux"
//Constants
import { EColor } from "Constants/Colors"
//Icons
import { ReactComponent as Sun } from "Assets/Icons/sun.svg"
import { ReactComponent as Moon } from "Assets/Icons/moon.svg"
//Redux
import { store } from "Stores"
import { setDarkMode } from "Stores/App/Creators"
//Styles
import { ThemeChangerStyle } from "./ThemeChanger.styles"
//Types
import { TRootState } from "Types/GlobalTypes"
const ThemeChanger: React.FC = (): ReactElement => {
//react-redux selector
const { darkMode } = useSelector((state: TRootState) => state.app)
//Toggle dark mode
const handleToggleTheme = () => {
store.dispatch(setDarkMode(!darkMode))
}
return (
<ThemeChangerStyle
as={motion.div}
animate={{
//Change the background color and border based on darkMode value
backgroundColor: darkMode ? EColor.CONTAINER_DARK : EColor.CONTAINER,
border: `2px solid ${darkMode ? EColor.CONTAINER : EColor.CONTAINER_DARK}`,
}}
onClick={handleToggleTheme}
>
<motion.div
animate={{
//Move the moon icon up if darkMode is true, move back down if false
x: "50%",
y: darkMode ? "-150%" : "5%",
transition: {
y: {
duration: 0.5,
type: "spring",
},
},
}}
>
<Moon style={{ width: 20 }} />
</motion.div>
<motion.div
animate={{
//Move the sun icon down if darkMode is true, move back up if false
x: "-50%",
y: darkMode ? "5%" : "150%",
transition: {
y: {
duration: 0.5,
type: "spring",
},
},
}}
>
<Sun style={{ width: 20 }} />
</motion.div>
</ThemeChangerStyle>
)
}
export default ThemeChanger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment