CSS-in-JS વગર ડાયનેમિક થીમિંગ

હું styled-components નો મોટો ચાહક હતો. મને તેની લવચીકતા (flexibility) ખૂબ ગમતી હતી. પછી મને એક મુશ્કેલીનો સામનો કરવો પડ્યો.

એક પ્રોજેક્ટમાં runtime weight ઘટાડવાની જરૂર હતી. મેં CSS Modules અને native CSS અજમાવવાનું નક્કી કર્યું. પરિણામે મને આશ્ચર્યચકિત કરી દીધો. મેં મારા પ્રોજેક્ટ્સમાંથી styled-components, Emotion, અને goober કાઢી નાખ્યા. મને ખરેખર જરૂર હતી તેવી કોઈ પણ વસ્તુ ગુમાવવી પડી નહીં.

સૌથી મોટો ફાયદો માત્ર પરફોર્મન્સ જ નહોતો. તે સ્ટાઇલિંગ ડિપેન્ડન્સી (styling dependency) દૂર કરવાનો હતો. એક પ્રોજેક્ટમાં, CSS-in-JS runtime ક્લાયન્ટ બંડલના 30% ભાગ રોકતું હતું.

Plain CSS હવે ઘણું આગળ વધી ગયું છે. હવે તમારે આ કાર્યો માટે ભારે JS libraries ની જરૂર નથી:

• Nesting: native CSS nesting નો ઉપયોગ કરો. • Color shifts: color-mix() નો ઉપયોગ કરો. • Specificity control: @layer નો ઉપયોગ કરો. • Responsive components: container queries નો ઉપયોગ કરો.

અહીં તમે માત્ર એક ફાઇલ અને custom properties નો ઉપયોગ કરીને થીમ કેવી રીતે બનાવી શકો છો તે દર્શાવેલ છે.

  1. CSS ફાઇલમાં tokens વ્યાખ્યાયિત કરો.
:root {
  --color-bg: #ffffff;
  --color-text: #1a1a1a;
  --color-accent: #3c7dc4;
}

[data-theme="dark"] {
  --color-bg: #14161a;
  --color-text: #f5f5f0;
  --color-accent: #6aa6e8;
}
  1. તમારા components માં તે variables નો ઉપયોગ કરો.
.button {
  background: var(--color-accent);
  color: var(--color-bg);
}
  1. માત્ર એક attribute બદલીને થીમ સ્વિચ કરો.
function setTheme(theme) {
  document.documentElement.dataset.theme = theme;
  localStorage.setItem("theme", theme);
}

Components ને ThemeProvider ની જરૂર નથી. તેમને re-render કરવાની પણ જરૂર નથી. બ્રાઉઝર cascade દ્વારા અપડેટ હેન્ડલ કરે છે. આનાથી તમારું મોટાભાગનું એપ Server Components માં રહે છે.

પેજ લોડ વખતે ખોટી થીમનો "flash" ટાળવા માટે, તમારા HTML head માં એક નાનકડા inline script નો ઉપયોગ કરો:

<script>
  const t = localStorage.getItem("theme") || 
  (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
  document.documentElement.dataset.theme = t;
</script>

runtime પર સ્ટાઇલ જનરેટ કરવા માટે JS નો ઉપયોગ કરવાનું બંધ કરો. તમારા tokens માટે native CSS variables નો ઉપયોગ કરો. તેનાથી કોડ ઓછો થશે અને લોડ ટાઇમ ઝડપી બનશે.

Source: https://dev.to/kirill_c_7b35589230/dynamic-theming-without-css-in-js-d7e