I am trying to use Selly.gg's embed script that will load a modal once a button with a data attribute is clicked.
https://selly.gg/help/article/embed-a-product-on-a-website
Using next.js, I am adding this in _document.js
class MyDocument extends Document {
render() {
return (
<html lang="en">
<Head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
/>
<meta name="theme-color" content={theme.palette.primary.main} />
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700&display=swap" rel="stylesheet"/>
<script src="https://embed.selly.gg" key="selly"></script>
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
MyDocument.getInitialProps = async ctx => {
effects.
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheets.collect(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: [
<React.Fragment key="styles">
{initialProps.styles}
{sheets.getStyleElement()}
</React.Fragment>,
],
};
};
export default MyDocument;
And loading the data for the button via ajax and and useContext.
export const ProductsContext = createContext();
export const ProductsProvider = props => {
const [categories, setCategories] = useState({});
const [products, setProducts] = useState({});
const [orders, setOrders] = useState({});
const [loading, setLoading] = useState(true);
useEffect(() => {
(async () => {
const [categoriesResult, productsResult, ordersResult] = await Promise.all([fetch('/api/categories'), fetch('/api/products'), fetch('/api/orders')]);
setCategories(await categoriesResult.json());
setProducts(await productsResult.json());
setOrders(await ordersResult.json());
setLoading(false);
})();
}, []);
return (
<ProductsContext.Provider value={ { products, categories, orders, loading } }>
{props.children}
</ProductsContext.Provider>
);
}
And being passed to ProductItem:
const ProductItem = (props) => {
const { product } = props;
return (
<Grid item md={4} className="product-item">
<h3 className="product-item-title"> { product.title } </h3>
<ReactMarkdown source={product.description.split("\n")[0]} />
<Grid container>
<Grid item md={3} className="product-item-price">
${product.price}
</Grid>
<Grid item md={9} className="product-item-button">
<Button variant="contained" color="primary" data-selly-product={product.id}>
Buy
</Button>
</Grid>
</Grid>
</Grid>
);
}
However, when clicking on a button, it will not do anything, no events will fire and the modal won't pop up.
I did build this once, however all of the code, including fetching data was in one large file, and that worked. So I know it is possible, just not sure how to do that in this cleaned up and organized way with useContext.
How can I do this?
from Using third parties scripts in next.js head with click events
No comments:
Post a Comment