Home > OS >  How to change icon while also doing a changeTheme with onClick in react js?
How to change icon while also doing a changeTheme with onClick in react js?

Time:04-04

I have succeded in creating a icon click to change the colorscheme of my website (line 21 and changeTheme), but when I click the icon I would also like it to change from FaRegMoon to FaRegSun and vice versa (i.e when I click it once it should change to FaRegSun and when I click it another time it should change to FaRegMoon

current code:

import React, {useState} from 'react'
import { FaRegMoon, FaRegSun } from "react-icons/fa"
import "./index.sass"

const changeTheme = () => {
    const item = localStorage.getItem("theme")
    let theme;
    if (item === "light") {
        theme = "";
        localStorage.setItem('theme', "")
    } else {
        theme = "light"
        localStorage.setItem('theme', 'light')
    }
    localStorage.setItem('theme', theme)
    document.body.className = localStorage.getItem("theme");
}

const ThemeToggle = () => {
    return (
        <div className='theme-toggle-button'>
            <FaRegMoon size={20} onClick={() => changeTheme() }/>
        </div>
    )
}

export default ThemeToggle;

CodePudding user response:

1.) Add a state for your icon inside ThemeToggle function

const [icon, setIcon] = useState('FaRegMoon')

2.) Add a parameter to your changeTheme function.

const changeTheme = (iconName) => { ... }

3.) Add the name of the icon argument you want to change to upon clicking

<FaRegMoon size={20} onClick={() => changeTheme('FaRegSun') }/>

4.) Refactor your ThemeToggle code (I used a ternary operator in returning a value for icon)

const ThemeToggle = () => {
    const [icon, setIcon] = useState('FaRegMoon')

    //place your changeTheme function here with the added code

    const themeIsLight = (icon === 'FaRegSun');
    const Icon = themeIsLight ? <FaRegSun size={20} onClick={() => changeTheme('FaRegMoon') }/>
                              : <FaRegMoon size={20} onClick={() => changeTheme('FaRegSun') }/>
    return (
        <div className='theme-toggle-button'>
            {Icon}
        </div>
    )
}

5.) lastly, refactor your changeTheme function. The component would re-render depending on the theme that is passed on to the setState function. add this line of code on the last line of changeTheme function. Hoped this helped brother.

setIcon(iconName)

  • Related