Skip to content

Instantly share code, notes, and snippets.

@configurator
Created November 3, 2019 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save configurator/920c1ce04d07d45d5e6d0b11907534d2 to your computer and use it in GitHub Desktop.
Save configurator/920c1ce04d07d45d5e6d0b11907534d2 to your computer and use it in GitHub Desktop.
Using components that require a loaded script using react-load-script
import React from 'react';
import Loader from './loader';
const drawChart = (data, div) => {
// omitted
// Can use the loaded script safely
}
export default ({data}) => (
<Loader>
<div ref={ref => drawChart(data, ref)} />
</Loader>
)
import React from 'react';
import Script from 'react-load-script';
export default class extends React.Component {
constructor(props) {
super(props);
this.state = { loading: true, error: false, loaded: false };
}
render() {
return (
<>
<Script
url="https://www.gstatic.com/charts/loader.js"
onError={() =>
this.setState({ loading: false, error: true })
}
onLoad={async () => {
try {
await google.charts.load('current', {
packages: ['corechart'],
});
this.setState({ loading: false, loaded: true });
} catch (e) {
this.setState({ loading: false, error: true })
}
}}
/>
{this.state.loading && 'Loading chart...'}
{this.state.error && 'An error occured while loading the chart'}
{this.state.loaded && this.props.children}
</>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment