Files
Matilda Landström 5272bbc023 Merged in fix/Sj-widget-error (pull request #3332)
refactor loading of SJ widget to avoid undefined window

* refactor loading of widget to avoid undefined window


Approved-by: Bianca Widstam
Approved-by: Erik Tiekstra
Approved-by: Joakim Jäderberg
Approved-by: Anton Gunnarsson
2025-12-17 13:35:02 +00:00

49 lines
1.2 KiB
TypeScript

"use client"
import Script from "next/script"
import { useEffect, useRef, useState } from "react"
import useLang from "@/hooks/useLang"
const SJSupportedLangs = ["en", "sv"] as const
export function SJWidget() {
const lang = useLang()
const [scriptInitialized, setScriptInitialized] = useState(
() => typeof window !== "undefined" && !!window.SJ?.widget?.init
)
const componentInitialized = useRef(false)
useEffect(() => {
if (!scriptInitialized) return
if (componentInitialized.current) return
if (!window.SJ?.widget?.init) return
window.SJ.widget.init({
micrositeId: "12952d0f-c70f-452c-9598-6586a64c7b60",
language: isSJSupportedLang(lang) ? lang : "en",
})
componentInitialized.current = true
}, [lang, scriptInitialized])
return (
<>
<Script
src="https://www.sj.se/microsite-widget/microsite-widget.min.js"
strategy="lazyOnload"
onLoad={() => setScriptInitialized(true)}
/>
<div id="sj-widget">&nbsp;</div>
</>
)
}
function isSJSupportedLang(
lang: string
): lang is (typeof SJSupportedLangs)[number] {
return SJSupportedLangs.includes(lang as (typeof SJSupportedLangs)[number])
}