javascripttailwind-cssqwik

Tailwind style not fully applied in dangerouslySetInnerHtml content


I have a HTML file with Tailwind styles that is saved in my database, so it should be fetched first which will have the result in a HTML string. It will be placed in dangerouslySetInnerHtml, the code is like this (I'm using Qwik)

export const useHTML = routeLoader$(async (path) => {
    // const domainName = path.url.host
    let domainName = path.url.host
    let htmlFile = ''

    if (path.url.host === 'localhost:5173') {
        domainName = 'page.id'
    }

    if (path.pathname) {
        htmlFile = `linkToMyFile/index.html`
    } else {
        htmlFile = `linkToMyFile/index.html`
    }

    const responseHtml = await fetch(htmlFile);

    return (await responseHtml.text() as string)
});

export default component$(() => {

    const htmlContent = useHTML().value;

    const htmlString: string = htmlContent.toString();

    return (
        <>
            <div dangerouslySetInnerHTML={htmlContent} />
        </>
    )
})

I also made a custom config for styling. I modify the tailwind.config.js to match the style from the fetched html code. the Tailwind config code looks like this

export default {
  content: ['./src/**/*.{js,ts,jsx,tsx,mdx}'],
  theme: {
    screens: {
        xs: '480px',
        sm: '640px',
        md: '768px',
        lg: '1024px',
        xl: '1280px',
        '2xl': '1400px',
    },
    colors: {
        current: 'currentColor',
        transparent: 'transparent',

        black: '#000',
        white: '#fff',

        //the rest of the code
    },
    fontWeight: {
        hairline: '100',
        thin: '200',
        light: '300',
        normal: '400',
        medium: '500',
        semibold: '600',
        bold: '700',
        extrabold: '800',
        black: '900',
    },
    fontFamily: {
        body: '"Clash Display"',
        heading: '"Clash Display"',
        sans: 'ui-sans-serif',
        serif: 'ui-serif, Georgia',
    },

//the rest of the default style code

The result is not like what I expected it to be. It seems the issue is probably in my fetched html code that I placed in dangerouslySetInnerHtml. The Tailwind config is applied before the fetching process done. I tried to write the code directly inside the prop, it works fine. but it should be dynamic so the fetching process is a must.


Solution

  • If the HTML files are on the same file system as where Tailwind compiles, consider adding content file globs to cover these files. Otherwise, you may need to look at configuring safelist to tell Tailwind to compile CSS rules for classes it never sees.