1
votes

I don't know much about styled-components, I am using a toggle switch to change themes and my theme does switch from dark to light but the icons I'm using don't switch icons. The icons are valid, when I switch the order of the component the Moon icon shows only instead, I'm guessing this is something with syntax?

import React from 'react'
import { func, string } from 'prop-types';
import styled from 'styled-components';
import { ReactComponent as MoonIcon } from '../components/icons/moon.svg';
import { ReactComponent as SunIcon } from '../components/icons/sun.svg';

const ToggleContainer = styled.button`
  background: ${({ theme }) => theme.gradient};
  border: 2px solid ${({ theme }) => theme.toggleBorder};
  border-radius: 30px;
  cursor: pointer;
  display: flex;
  font-size: 0.5rem;
  justify-content: space-between;
  margin: 0 auto;
  overflow: hidden;
  padding: 0.5rem;
  position: relative;
  width: 8rem;
  height: 4rem;

  svg {
    height: auto;
    width: 2.5rem;
    transition: all 0.3s linear;
    
    // sun icon
    &:first-child {
      transform: ${({ lightTheme }) => lightTheme ? 'translateY(0)' : 'translateY(100px)'};
    }
    
    // moon icon
    &:nth-child(2) {
      transform: ${({ lightTheme }) => lightTheme ? 'translateY(-100px)' : 'translateY(0)'};
    }
  }
`;
const Toggle = ({ theme, toggleTheme }) => {
    
  const isLight = theme === 'light';
  return (
    <ToggleContainer onClick={toggleTheme} >
      <MoonIcon />
      <SunIcon />
    </ToggleContainer>
  );
};

Toggle.propTypes = {
  theme: string.isRequired,
  toggleTheme: func.isRequired,
}

export default Toggle;

lightmode

darkmode

1
lol i have same question, did u figure it out? - John D

1 Answers

1
votes

Add lightTheme={isLight} to this code

At: <ToggleContainer onClick={toggleTheme} >

Final: <ToggleContainer onClick={toggleTheme} lightTheme={isLight}>

Also, you can play with transform like below for switching between,

`&:first-child {
  transform: ${({ lightTheme }) => lightTheme ? 'translateX(0px)' : 'translateX(-150px)'};
}    

&:nth-child(2) {
  transform: ${({ lightTheme }) => lightTheme ? 'translateX(100px)' : 'translateX(0px)'};
}`