I have 2 components in my react app for now: App and Navbar I am trying to dynamically load css (4 different themes from bootswatch) on user click (theming in short)
Below are the components:
App.js
class App extends Component {
state = {};
availableThemes = ["lux", "sketchy", "flatly", "darkly"];
constructor() {
super();
this.changeTheme("flatly");
ReactDOM.findDOMNode;
}
changeTheme = themeName => {
console.log("Theme", themeName);
if (this.availableThemes.indexOf(themeName) < 0) {
alert("Theme not available");
} else {
import(`./themes/${themeName}/bootstrap.min.css`)
.then(() => {
console.log("Theme loaded", themeName);
})
.catch(() => {});
}
};
render() {
return (
<NavBar
themesList={this.availableThemes}
onThemeChange={this.changeTheme}
/>
);
}
}
Navbar.jsx:
class NavBar extends Component {
state = {};
render() {
const { themesList, onThemeChange } = this.props;
return (
<Navbar bg="dark" variant="dark" expand="lg">
<Navbar.Brand>WiLite</Navbar.Brand>
<Navbar.Collapse style={{ paddingLeft: 25 + "%" }}>
<Form inline>
<FormGroup>
<FormControl
type="text"
placeholder="Search"
className="mr-sm-2"
/>
<Button variant="outline-light">Search</Button>
</FormGroup>
</Form>
<Nav>
<NavDropdown title="Theme">
{themesList.map(theme => {
return (
<NavDropdown.Item
key={v4()}
onClick={() => {
onThemeChange(theme);
}}
>
{theme}
</NavDropdown.Item>
);
})}
</NavDropdown>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
Now the output of changeTheme
is very random. Sometimes the theme gets applied, sometimes it doesn't and sometimes I get a mixture of both the themes (the one I requested and the one which was already loaded).
Can someone please suggest how can I accomplish this?