ES2015: How can I simplify an if statement with assignment?

- 1 answer

Ad

I am building a React component that returns diverse tags based on a condition. The code is the following:

// Header.jsx

import React from 'react';

const Header = ({...props}) => {
	let Tag;
	if (props.h1)
		Tag = 'h1';
	else if (props.h2)
		Tag = 'h2';
	else if (props.h3)
		Tag = 'h3';
	else if (props.h4)
		Tag = 'h4';
	else if (props.h5)
		Tag = 'h5';
	else
		Tag = 'h6';

	return (
		<Tag>
			{ children }
		</Tag>
	);
}

export default Header;

I though ES2015 would support if as expressions, so I tried let Tag = (if (expression) [...]);, but it seems that it doesn't support. How can I simplify this snippet?

Ad

Answer

Ad

I solved my problem by dynamic searching for the tags with regex. The code ended like this:

// Header.jsx

import React from 'react';

const Header = ({children, ...other}) => {
	let Tag = (() => {
		for(let key in other)
			if (/(h[1-6])/.exec(key)) return key;
		return 'h6';
	})();

	return (
		<Tag {...other}>
			{ children }
		</Tag>
	);
}

export default Header;

What do you think about this solution?

Ad
source: stackoverflow.com
Ad