fdalex
fdalex

Reputation: 13

Theming with React

I'm working on an old app with CakePHP 2 and I want to modernize it from scratch by making a new app based on Laravel and ReactJs, full API REST. Actually I have an admin page to apply a specific theme to a store. For example I have www.store1.com and www.store2.com. When I enter the url www.store1.com it loads the selected theme and templates, it loads default values if nothing is defined, using the theme system of CakePHP 2 with a structure like this :

I'm pretty new with Laravel and React, what I'm looking now is how achieve something similar with React :

Any help is welcomed, thanks

I've read many tutorials about react and themes, styled-components might be a hint, what i find is mostly theme switcher like light/dark theme but not sure that it's what I want.

Upvotes: 0

Views: 683

Answers (1)

rachitiitr
rachitiitr

Reputation: 521

The currentThemeLink variable is used to keep track of the currently applied theme's CSS file. Before adding the new theme's CSS file, the code checks if a theme was previously loaded. If so, it removes the previous link tag from the document. This ensures that only one theme's CSS file is applied at a time, and the cleanup is handled properly when switching themes.

Remember to replace /path-to-themes/ with the actual path to your theme CSS files.

// Variable to store the reference to the currently loaded theme CSS file
let currentThemeLink = null;

function loadThemeCSS(themeName) {
  // Create a new link element for the selected theme
  const newThemeLink = document.createElement('link');
  newThemeLink.rel = 'stylesheet';
  newThemeLink.type = 'text/css';
  newThemeLink.href = `/path-to-themes/${themeName}.css`; // Replace with the actual path

  // If a theme was previously loaded, remove it before adding the new one
  if (currentThemeLink) {
    document.head.removeChild(currentThemeLink);
  }

  // Add the new theme's CSS file to the document
  document.head.appendChild(newThemeLink);

  // Update the reference to the current theme link
  currentThemeLink = newThemeLink;
}


// Example usage when the user selects a theme:
function handleThemeChange(themeName) {
  loadThemeCSS(themeName);
}

// Render your UI element for theme selection
<button onClick={() => handleThemeChange('theme-light')}>Light Theme</button>
<button onClick={() => handleThemeChange('theme-dark')}>Dark Theme</button>

Upvotes: 1

Related Questions