'Variable name is treated as string while I want to fetch data from object
I am trying to get the value of themes.green and if I wrote it directly then I can access it easily but whenever I wrote var choose = themes.green it is treated as string and I can't access my object. Value of choose is a function parameter eg(themes.green or themes.orange).
import { createContext,useState } from "react";
const themes ={
orange:{
backgroundColor:'#DA661B',
color:'white'
},
green:{
backgroundColor:'#0d7e65',
color:'white'
},
blue:{
backgroundColor:'#0375A5',
color:'white'
}
}
export const ThemeContext = createContext();
export const ThemeProvider = ({children}) => {
const [ColorName, setColorName] =useState(themes.blue);
const theme = ColorName;
const toggleTheme = (choose) =>{
console.log(choose)
if(choose==themes.green)
console.log('same')
else console.log('notsame');
setColorName(choose);
}
return(
<ThemeContext.Provider value={[{ColorName, theme},toggleTheme]}>
{children}
</ThemeContext.Provider>
)
}
Using in Navbar components
import React from 'react'
import { useContext } from 'react'
import { ThemeContext } from '../../contexts/Theme'
import './Navbar.css'
const Navbar = () => {
const [{theme,ColorName},toggleTheme] = useContext(ThemeContext)
return (
<div>
<nav className='navbar-container' style={{background:theme.backgroundColor,color:theme.color}}>
<div>SQL COMPILER</div>
<button onClick={()=>toggleTheme('themes.green')}></button>
<div id='atlan-logo-text'>test</div>
</nav>
<div>
</div>
</div>
)
}
export default Navbar
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
