Skip to content

Instantly share code, notes, and snippets.

@bensampaio
Last active January 7, 2020 12:30
Show Gist options
  • Save bensampaio/54947468bc0d6614aa944bd1ac555fd5 to your computer and use it in GitHub Desktop.
Save bensampaio/54947468bc0d6614aa944bd1ac555fd5 to your computer and use it in GitHub Desktop.
Example of an iframe component that intercepts form submissions
class IFrame extends PureComponent {
// ...
getSnapshotBeforeUpdate(prevProps, prevState) {
const snapshot = {
hash: false,
redirect: false,
};
const { location: prevLocation } = prevProps;
const { location: nextLocation } = this.props;
const iframeLocation = this.iframeElement.current.contentWindow.location;
const { hash: prevHash, pathname: prevPathname, search: prevSearch } = prevLocation;
const { hash: nextHash, pathname: nextPathname, search: nextSearch } = nextLocation;
const { hash: iframeHash, pathname: iframePathname, search: iframeSearch } = iframeLocation;
// If the iframe path is already the next path then it means a submit occurred
if ((iframePathname !== prevPathname && iframePathname === nextPathname) || (iframeSearch !== prevSearch && iframeSearch === nextSearch)) {
snapshot.redirect = true;
}
// If the iframe path has already the next hash then it means the user navigated inside the iframe
if (iframePathname === prevPathname && iframePathname === nextPathname && iframeSearch === prevSearch && iframeSearch === nextSearch && iframeHash !== prevHash && iframeHash === nextHash) {
snapshot.hash = true;
}
return snapshot;
}
componentDidUpdate(prevProps, prevState, snapshot) {
const { hash, redirect } = snapshot;
const { location: prevLocation } = prevProps;
const { location: nextLocation } = this.props;
const { key: prevKey } = prevLocation;
const { key: nextKey, hash: nextHash, pathname: nextPathname, search: nextSearch } = nextLocation;
if (nextKey !== prevKey && !hash && !redirect) {
this.setState({
location: {
hash: nextHash,
key: prevKey + nextKey,
pathname: nextPathname,
search: nextSearch,
},
});
}
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment