Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
one-line React component for conditionally wrapping children
import React from 'react';
const ConditionalWrap = ({condition, wrap, children}) => condition ? wrap(children) : children;
const Header = ({shouldLinkToHome}) => (
<div>
<ConditionalWrap
condition={shouldLinkToHome}
wrap={children => <a href="/">{children}</a>}
>
<img src="logo.png"/>
</ConditionalWrap>
</div>
)
@TheBox193

This comment has been minimized.

Copy link

TheBox193 commented Oct 9, 2018

Some Unit tests:

describe('ConditionalWrap', () => {
	it('Should wrap when true', () => {
		const wrapper = shallow(
			<ConditionalWrap condition={true} wrap={children => <a href='/'>{children}</a>} >
				<img src='image.png' />
			</ConditionalWrap>
		);

		expect(wrapper.find('a').length).toBe(1);
		expect(wrapper.find('img').length).toBe(1);
	});
	it('Should not wrap when false', () => {
		const wrapper = shallow(
			<ConditionalWrap condition={false} wrap={children => <a href='/'>{children}</a>} >
				<img src='image.png' />
			</ConditionalWrap>
		);

		expect(wrapper.find('a').length).toBe(0);
		expect(wrapper.find('img').length).toBe(1);
	});
	it('Should not wrap when undefined', () => {
		const wrapper = shallow(
			<ConditionalWrap wrap={children => <a href='/'>{children}</a>} >
				<img src='image.png' />
			</ConditionalWrap>
		);

		expect(wrapper.find('a').length).toBe(0);
		expect(wrapper.find('img').length).toBe(1);
	});
});
@RedTn

This comment has been minimized.

Copy link

RedTn commented Nov 2, 2018

This fails if condition = false, and you are returning more than one child on React 15, if so I would change line 3 to

const ConditionalWrap = ({condition, wrap, children}) => condition ? wrap(children) : <div>children</div>;
@peacefulseeker

This comment has been minimized.

Copy link

peacefulseeker commented Jan 2, 2019

This fails if condition = false, and you are returning more than one child on React 15, if so I would change line 3 to

const ConditionalWrap = ({condition, wrap, children}) => condition ? wrap(children) : <div>children</div>;

or even using new React Fragments short syntax;
https://reactjs.org/docs/fragments.html#short-syntax

const ConditionalWrap = ({condition, wrap, children}) => condition ? wrap(children) : <>{children}</>;

@Jianyi-Ren

This comment has been minimized.

Copy link

Jianyi-Ren commented Sep 17, 2019

Thanks for sharing the unit test! How would you test the ConditionalWrap if it is defined within component render(){}?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.