Skip to content

Commit

Permalink
Loader component
Browse files Browse the repository at this point in the history
  • Loading branch information
kennedyrose committed May 4, 2018
1 parent 8961eb9 commit cd79089
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 23 deletions.
6 changes: 1 addition & 5 deletions dev/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ class Forms extends React.Component{
portalId='4111488'
formId='82941100-1bbc-406e-8d63-f7232304738c'
onSubmit={() => console.log('SUBMIT')}
/>
<HubspotForm
portalId='4111488'
formId='82941100-1bbc-406e-8d63-f7232304738c'
onSubmit={() => console.log('SUBMIT')}
loading={<p>Loading...</p>}
/>
</div>
)
Expand Down
53 changes: 35 additions & 18 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,58 +7,75 @@ let scriptLoaded = false
class HubspotForm extends React.Component {
constructor(props) {
super(props)
this.state = {}
this.state = {
loaded: false
}
this.id = globalId++
this.createForm = this.createForm.bind(this)
this.findFormElement = this.findFormElement.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
createForm() {
if (window.hbspt) {
const options = {
...this.props,
let props = {
...this.props
}
delete props.loading
let options = {
...props,
target: `#${this.el.getAttribute(`id`)}`,
}
window.hbspt.forms.create(options)
this.findFormElement()
return true
}
else{
setTimeout(this.createForm, 1)
}
}
loadScript() {
if(scriptLoaded || this.props.noScript) return
scriptLoaded = true
const script = document.createElement(`script`)
script.onload = this.createForm
let script = document.createElement(`script`)
script.src = `//js.hsforms.net/forms/v2.js`
document.head.appendChild(script)
}
findFormElement(){
let form = this.el.querySelector(`form`)
if(form){
form.addEventListener(`submit`, this.props.onSubmit)
this.setState({ loaded: true })
form.addEventListener(`submit`, this.onSubmit)
}
else{
setTimeout(this.findFormElement, 1)
}
}
onSubmit(){
let interval = setInterval(() => {
if(!this.el.querySelector(`form`)){
clearInterval(interval)
if(this.props.onSubmit){
this.props.onSubmit()
}
}
}, 1)
}
componentDidMount() {
if (!scriptLoaded && !this.props.noScript) {
this.loadScript()
}
else {
this.createForm()
}
this.loadScript()
this.createForm()
this.findFormElement()
}
render() {
return (
<div id={`reactHubspotForm${this.id}`} ref={el => this.el = el} />
<div>
<div
ref={el => this.el = el}
id={`reactHubspotForm${this.id}`}
style={{ display: this.state.loaded ? 'block' : 'none'}}
/>
{!this.state.loaded && this.props.loading}
</div>
)
}
}

HubspotForm.defaultProps = {
onSubmit: () => {}
}

export default HubspotForm

0 comments on commit cd79089

Please sign in to comment.