Last active
November 5, 2018 17:25
-
-
Save karol-majewski/f35598aeb053e0a0f5771e1ddeaa7bc9 to your computer and use it in GitHub Desktop.
Wrapping React Elements conditionally
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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"/>} | |
/> | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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