I'm trying to embed a Typeform contact form in my Gatsby React website. All the examples I've seen use the basic html button
as an example, however that falls away from my website's theme. This is an example of the code I'm using to embed the typeform:
import React, { Component } from 'react';
import * as typeformEmbed from '@typeform/embed';
class ContactInfo extends Component {
componentDidMount() {
const popup1 = typeformEmbed.makePopup('URL', {
mode: 'drawer_right',
autoclose: 3000,
hideHeaders: true,
onSubmit: function () {
console.log('Typeform successfully submitted');
}
});
document.getElementById('bt-popup').addEventListener('click', function () {
popup1.open();
});
}
render() {
return (
<div>
<button id="bt-popup" class="my-button">
Popup
</button>
</div>
);
}
}
export default ContactInfo;
However, I have my own button component created here which I would like to use instead of the one in the example. Here is the code:
import React from 'react';
import PropTypes from 'prop-types';
import * as Styled from './styles';
const Button = ({ primary, block, children }) => (
<Styled.Button primary={primary} block={block} whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
{children}
</Styled.Button>
);
Button.propTypes = {
primary: PropTypes.bool,
block: PropTypes.bool,
children: PropTypes.any.isRequired
};
export default Button;
How do I replace the <button>
with my own component <Button>
so that it is in keeping with the site theme?
Do you mean?
import React, { Component } from 'react';
import * as typeformEmbed from '@typeform/embed';
import Button from 'path/to/button/component'
class ContactInfo extends Component {
componentDidMount() {
const popup1 = typeformEmbed.makePopup('URL', {
mode: 'drawer_right',
autoclose: 3000,
hideHeaders: true,
onSubmit: function () {
console.log('Typeform successfully submitted');
}
});
document.getElementById('bt-popup').addEventListener('click', function () {
popup1.open();
});
}
render() {
return (
<div>
<Button id="bt-popup" class="my-button">
Popup
</Button>
</div>
);
}
}
export default ContactInfo;
Note: you may need to use createPopop
(^1.01
) instead of makePopup
depending on your Typeform version.
Keep in mind that accessing directly to the DOM (as you do use document.getElementById
) is not the best approach in terms of best practices because it has a huge performance impact (such jQuery for example). Indeed, this is why you are using React, which creates a virtual DOM. You can replicate the same behavior using useRef
hook.