I'm trying to create a Dark Mode in React. For that I need a "mega-variable" that will be accessible from anywhere on the component tree and look like :
let darkMode = false
and when that will be toggled, in a chosen component I will have the ability to write something like that :
<button>{darkMode ? "Light Mode" : "Dark Mode"}</button>
I tried to do it with MobX but it didn't work. It doesn't re-render like in a state change. What can I do?
Be careful with global variables
. Actually given React's flow it's pretty hard to even achieve that (perhaps using window
object?). What you want could be done using Context API
. It's a decoupled way to pass props
through your components. By wrapping the highest level of your application with a Provider
you could access it from anywhere (inside the same tree):
const {Provider, Consumer} = React.createContext()
const App = () =>{
<Provider value={{theme: 'dark'}}>
<MyComponents />
</Provider>
}
And inside any component from this tree:
const Component = () =>{
return(
<Consumer>
{context => console.log(context.theme) /*dark*/}
</Consumer>
)
}
There are other alternatives like redux
but seems an overkill to your use case.