Guard Components
Different ways of creating a Higher Order Guard component in React
by Pavan Podila
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-dom.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Babel + JSX
function Guard({condition, children}) {
return condition ? children : null;
};
function guard(condition, Component) {
return class Guarded extends React.Component {
render() {
return condition ? <Component {...this.props} /> : null;
}
}
}
function guardWith(condition) {
return function(Component) {
return guard(condition, Component);
}
}
const AdminComponent = guard(true, props=>{
return <h1>You are an Admin, I think</h1>;
});
@guardWith(true)
class AdvancedAdminComponent extends React.Component {
render() {
return <h2>Advanced Admin Component</h2>;
}
}
const root = (
<div>
<Guard condition={false}>
<h2>Not an Admin!!</h2>
</Guard>
<Guard condition={true}>
<h2>Looks like you are an Admin</h2>
</Guard>
<AdminComponent />
<AdvancedAdminComponent />
</div>
);
ReactDOM.render(root, document.getElementById('container')
);