Created
November 3, 2019 09:22
-
-
Save configurator/920c1ce04d07d45d5e6d0b11907534d2 to your computer and use it in GitHub Desktop.
Using components that require a loaded script using react-load-script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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