I Want To Have a Toggle Switch For Dark & Light theme, How Do i Do it ?.
ayhamDev opened this issue · comments
Ayham commented
I Want To Have a Toggle Switch For Dark & Light theme, How Do i Do it ?.
Rafał Dzięgielewski commented
You can for example override SidebarFooter
:
componentLoader.override('SidebarFooter', <path to your file>)
SidebarFooter:
import React, { useCallback } from 'react';
import { useCurrentAdmin } from 'adminjs';
import axios from 'axios';
import { Box, Button, Icon } from '@adminjs/design-system';
import { styled, useTheme } from '@adminjs/design-system/styled-components';
const SidebarFooter: React.FC = () => {
const [currentAdmin, setCurrentAdmin] = useCurrentAdmin();
const theme = useTheme();
const toggleTheme = useCallback(async () => {
try {
const theme = currentAdmin.theme === 'light' ? 'dark' : 'light';
const response = await axios.put('/app/me', { theme });
const { updated, session } = response.data;
if (updated) {
setCurrentAdmin(session);
window.location.reload();
}
} catch (err) {
console.error(err);
}
}, [currentAdmin]);
const icon = currentAdmin.theme === 'dark' ? 'Sun' : 'Moon';
return (
<Box mt="lg" mb="md" data-css="sidebar-footer">
<Box flex justifyContent="center" mb="xl">
<ToggleButton onClick={toggleTheme} size="icon">
<Icon icon={icon} size={24} color={theme.colors.text} />
</ToggleButton>
</Box>
</Box>
);
};
export default SidebarFooter;
This will handle the frontend, but you need to add a new adminjs endpoint which modifies your user's session.
Express example (a file where you create AdminJS router):
const router = ExpressPlugin.buildAuthenticatedRouter(
admin,
// other settings
);
router.put('/me', (request, response) => {
const body = (request as any).fields ?? {};
const admin = { ...((request.session as any).adminUser ?? {}) };
let sessionUpdated = false;
// It's better to set all relevant values manually to avoid malforming the session object
if (body.theme) {
admin.theme = body.theme;
(request.session as any).adminUser = admin;
request.session.save();
sessionUpdated = true;
}
return response.send({
session: admin,
updated: sessionUpdated,
});
});