Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active November 5, 2018 17:25
Show Gist options
  • Save karol-majewski/f35598aeb053e0a0f5771e1ddeaa7bc9 to your computer and use it in GitHub Desktop.
Save karol-majewski/f35598aeb053e0a0f5771e1ddeaa7bc9 to your computer and use it in GitHub Desktop.
Wrapping React Elements conditionally
/**
* TypeScript version of the solution proposed by @kitze.
*
* @see https://gist.github.com/kitze/23d82bb9eb0baabfd03a6a720b1d637f
*/
import React from 'react';
interface Props<T = {}> {
condition: boolean;
render: (children: React.ReactElement<T> | null) => React.ReactElement<T> | null;
children: React.ReactElement<T> | null;
}
const ConditionalWrapper: React.SFC<Props> = ({ condition, render, children }) =>
condition
? render(children)
: children;
export default () => (
<ConditionalWrapper
condition={false}
render={children => <div>{children}</div>}
children={<img src="logo.png"/>}
/>
);
import * as React from 'react';
interface Options<P extends object, U extends object> {
content: React.ReactElement<P>;
wrapper: React.ReactElement<U>;
}
export const withConditionalWrapping = <P extends object, U extends object>({ content, wrapper }: Options<P, U>) =>
(shouldWrap: boolean) =>
shouldWrap
? React.createElement(wrapper.type, wrapper.props, content)
: content;
const decision = Math.random() > 0.5;
export default withConditionalWrapping({
content: <a href="http://gist.github.com" alt="See some nice Gists" />,
wrapper: <div />,
})(decision);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment