Home > Net >  Toggling button image in React
Toggling button image in React

Time:04-23

I'm trying to toggle an icon in a button in react but I've tried everything and nothing works. I can change the background/text color toggling onClick but I'm missing something to change the icon and I don't know what! Any help?

Here's my code: App.js

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useState } from "react";
import Layout from "./layout";
import ThemeContext, { themes } from "./theme-context";
import { faSun, faMoon } from '@fortawesome/free-solid-svg-icons'

function App() {

  const sun = <FontAwesomeIcon icon={faSun} />
  const moon = <FontAwesomeIcon icon={faMoon} />

  const [theme, setTheme] = useState(themes.dark)


  const toggleTheme = () => theme === themes.dark ? setTheme(themes.light) : setTheme(themes.dark)


  return (
    <ThemeContext.Provider value={theme}>
      <button onClick={toggleTheme}>


        {sun}



      </button>
      <Layout />
    </ThemeContext.Provider>
  );
}

export default App;

theme-context.js

import React from "react"


export const themes = {
    dark: {
        color: "white",
        background: "black",
        padding: "5px",
        width: "200px",
        textAlign: "center",
    },
    light: {
        color: "black",
        background: "white",
        padding: "5px",
        width: "200px",
        textAlign: "center",


    }

}

const ThemeContext = React.createContext(themes.dark)

export default ThemeContext;

layout.jsx

import React, { useContext } from "react";
import ThemeContext from "./theme-context";

const Layout = () =>{

const theme = useContext(ThemeContext)
return (
    <div style={theme} >
<p>This is your content</p>
</div>
)
}

export default Layout;

I have tried {themes.dark? : {sun} ? {moon}} but it didn't work.

CodePudding user response:

The {themes.dark? : {sun} ? {moon}} was very close to correct (concept-wise, the syntax is not correct though). What you needed to do instead is { theme === themes.dark ? sun : moon } With your original snippet, you were just checking to see if themes.dark was truthy, which will always return true because it is an object. What you needed to do was check to see if the current theme was the same as themes.dark.

Hope this helps.

CodePudding user response:

Because you do not have logic to change it in the code. You should update in this way

<button onClick={toggleTheme}>
  {theme === themes.dark ? moon : sun}
</button>
  • Related