Reputation: 83
I'm using Material UI's switch to change themes on a multi-page app. The only bug that happens is the switch does not move from left to right (ui functionality does not occur), but the onChange functionality is working fine. I played around with it, turns out that when I remove forceUpdate(), the material ui switch will work, but the component will not be rerendered. What in forceUpdate is preventing the switch functionality from working?
App.tsx :
import React from "react"
import {Switch, Route, BrowserRouter, Redirect} from "react-router-dom"
import Main from "./Main"
import {createMuiTheme, ThemeProvider} from "@material-ui/core";
class App extends React.Component<any, any>{
darkmode=true
theme=createMuiTheme({
palette:{
type:this.darkmode?"dark" : "light"
},
})
changeTheme=()=>{
this.darkmode=!this.darkmode;
this.theme = createMuiTheme({
palette:{
type:this.darkmode?"dark" : "light"
}
})
this.theme.spacing(10)
this.forceUpdate()
}
render(){
return(
<div>
<BrowserRouter>
<Switch>
<Route path="/" component={()=>
<Main theme={this.theme} changeTheme={this.changeTheme} />
}
</Switch>
</BrowserRouter>
</div>
)
}
}
Main.tsx:
class Main extends React.Component<any,any>{
render(){
return(
<div>
<Switch onChange={()=>this.props.changeTheme()}></Switch>
<Switch></Switch>
</div>
)
}
}
Upvotes: 1
Views: 1190
Reputation: 1213
you didn't use states the UI will not rerender if you don't pass a new state
constructor(props) {
super(props);
this.state = {darkmode: true};
}
this.setState({
darkmode: !darkmode
});
the two piece of code here will help you the first one in the initialize of the state and the second is the update
By default, when your component’s state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().
take from react doc that explain what it's do basically it's rernder by force the component you should avoid to all use and make the read from the props and state
Upvotes: 0