Skip to content

Commit

Permalink
safely validate root prop for SSR #5
Browse files Browse the repository at this point in the history
  • Loading branch information
jscottsmith committed Feb 26, 2018
1 parent 9c0f178 commit 4ede0c4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Observed.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import validHTMLElement from './validHTMLElement';

class Observed extends Component {
static defaultProps = {
Expand All @@ -25,7 +26,7 @@ class Observed extends Component {
onChange: PropTypes.func,
onIntersect: PropTypes.func,
options: PropTypes.shape({
root: PropTypes.instanceOf(Element),
root: validHTMLElement,
rootMargin: PropTypes.string,
threshold: PropTypes.oneOfType([PropTypes.array, PropTypes.number]),
}),
Expand Down
24 changes: 24 additions & 0 deletions src/validHTMLElement.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// SSR safe Valid HTML Element prop check

export default function validHTMLElement(
props,
propName,
componentName = 'ANONYMOUS'
) {
if (typeof window === 'undefined') {
return null;
}

if (props[propName]) {
const value = props[propName];
const isValid = value instanceof window.Element;

if (!isValid) {
return new Error(
`Prop name "${propName}" in <${componentName}> must be an HTML DOM element.`
);
}
}

return null;
}

0 comments on commit 4ede0c4

Please sign in to comment.