Skip to content

Commit a1a0fae

Browse files
authored
Merge pull request #318 from HarvardOpenData/iframe-v3
more updates
2 parents dbeb188 + feb1def commit a1a0fae

File tree

1 file changed

+22
-26
lines changed

1 file changed

+22
-26
lines changed

web/src/components/article-layouts/article-body.js

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -6,55 +6,51 @@ import BlockContent from "../block-content";
66
import Container from "../core/container";
77
import { DiscussionEmbed } from "disqus-react";
88

9-
import React, { useEffect, useRef, useState } from "react";
9+
import React, { useEffect, useRef } from "react";
1010

11+
// Define the iframe serializer
1112
const serializers = {
1213
types: {
1314
iframe: ({ node }) => {
1415
const { url, caption } = node;
15-
const iframeRef = useRef(null);
16-
const [height, setHeight] = useState(400); // fallback height
16+
const containerRef = useRef(null);
1717

1818
useEffect(() => {
19-
function receiveMessage(e) {
20-
if (
21-
e.data &&
22-
typeof e.data === "object" &&
23-
e.data["datawrapper-height"]
24-
) {
25-
const chartId = Object.keys(e.data["datawrapper-height"])[0];
26-
const newHeight = e.data["datawrapper-height"][chartId];
27-
if (iframeRef.current) {
28-
iframeRef.current.style.height = `${newHeight}px`;
29-
setHeight(newHeight);
30-
}
31-
}
32-
}
19+
if (!url || !containerRef.current) return;
20+
21+
const match = url.match(/dwcdn\.net\/([^/]+)/);
22+
if (!match) return;
3323

34-
window.addEventListener("message", receiveMessage);
35-
return () => window.removeEventListener("message", receiveMessage);
36-
}, []);
24+
const chartId = match[1];
25+
const scriptId = `dw-script-${chartId}`;
26+
27+
if (!document.getElementById(scriptId)) {
28+
const script = document.createElement("script");
29+
script.src = `https://datawrapper.dwcdn.net/${chartId}/embed.js`;
30+
script.defer = true;
31+
script.id = scriptId;
32+
document.body.appendChild(script);
33+
}
34+
}, [url]);
3735

3836
const chartId = url.match(/dwcdn\.net\/([^/]+)/)?.[1];
3937

4038
return (
41-
<div style={{ width: "100%", margin: "2rem 0" }}>
39+
<div ref={containerRef} style={{ width: "100%", margin: "2rem 0" }}>
4240
<iframe
43-
ref={iframeRef}
4441
id={`datawrapper-chart-${chartId}`}
4542
title={caption || "Embedded chart"}
4643
src={url}
4744
scrolling="no"
4845
frameBorder="0"
46+
allowFullScreen
47+
data-external="1"
4948
style={{
5049
width: "0",
5150
minWidth: "100%",
5251
border: "none",
53-
height: `${height}px`,
54-
transition: "height 0.2s ease",
52+
height: "400px", // fallback height, will get resized
5553
}}
56-
allowFullScreen
57-
data-external="1"
5854
/>
5955
{caption && (
6056
<p

0 commit comments

Comments
 (0)