I have been trying to use createElement inside an if statement but it just doesn't work. The headerLink
is not recognized outside of the if statement.
Can someone explain what's missing?
What I have tried so far:
Declaring
headerLink
outside the if statement. This doesn't workIf I move the
appendChild
andremoveChild
inside the if statement, it starts to work. But, that would result in duplicate code since I will need to copy the same inside the else statementReact.useEffect(() => { const head = document.head; const scriptType = "text/css"; if (scriptType === "text/css") { const headerLink = document.createElement( "link" ); } else { const headerLink = document.createElement( "script" ); } // this line doesn't work - headerLink is not recognized head.appendChild(headerLink); return () => { // this line doesn't work - again, headerLink is not recognized head.removeChild(headerLink); }; }, []);