react-google-tag-manager
react-google-tag-manager copied to clipboard
<script> tag must not be included in a <div>
After paste <GoogleTagManager gtmId="GTM-mycode" /> after body opening i get error: <script> tag must not be included in a <div>
How can i fix? Can i remove wrappers of example?
Hey @mlimasolucoes,
the wrapper is used for a single purpose, returning a single node. See the documentation. As a quickfix you could change the wrapper to an element that doesn't throw an error. You can find a list of them here.
according to the GTM documentation the script tag needs to be a direct child of the body (god know's why—ugh) however that's not really possible with most react apps
Was just a warning. []'s
i fixed it by not including the <script>
in render()
and simply doing the eval
in componentDidMount()
e.g.:
type DefaultProps = {
additionalEvents: Object,
dataLayerName: string,
scriptId: string
};
type Props = DefaultProps & {
gtmId: string
};
class GoogleTagManager extends React.Component<DefaultProps, Props, void> {
static defaultProps: DefaultProps = {
additionalEvents: {},
dataLayerName: 'dataLayer',
scriptId: 'react-google-tag-manager-gtm'
};
componentDidMount() {
const gtm = buildGTM({
id: this.props.gtmId,
additionalEvents: this.props.additionalEvents,
dataLayerName: this.props.dataLayerName
});
if (!window[this.props.dataLayerName]) {
eval(gtm.scriptAsHTML().replace(/<\/?script>/g, ''));
}
}
render() {
const gtm = buildGTM({
id: this.props.gtmId,
additionalEvents: this.props.additionalEvents,
dataLayerName: this.props.dataLayerName
});
return gtm.noScriptAsReact();
}
}
export default GoogleTagManager;
can someone confirm if the GTM also works if inside a container, as in the example?
Or is there some kind of container that is recommended, because according to google's documentation it should be completely avoided to nest it.
I think it's obvious for most but it's worth mentioning that if you're doing server-side rendering then you can skip the componentDidMount
hook altogether.
@shri3k it wouldn't be isomorphic then
Unless for some reason your server side fails to load (on which I think you have bigger probelm than not loading this component) then yes, you'll need to rely on componentDidMount
to load this for you. But I've always felt that isomorphic meant server side first and then hand off to client. Never the other way around.
Is there an official fix for this issue?
Is this even a problem? Or is this error being detected because at the moment when the page first loads react hasn't replaced the DOM?