I'm trying to build a button-component which is able to have icons set before and after the element's children.
Therefore, the props are like this:
export interface IButtonProps {
children?: React.ReactNode;
leftIcon?: FontAwesomeIcon;
rightIcon?: FontAwesomeIcon;
}
whereas FontAwesomeIcon
is an enum holding the available icons.
In the button's render
-function I do check if there is an icon set. If so, there should be the icon and a whitespace between the children and the icon.
render(): JSX.Element {
let { children, leftIcon, rightIcon } = this.props;
return (
<button>
{leftIcon && <FontAwesome icon={leftIcon} />}
{leftIcon && " "}
{children}
{rightIcon && " "}
{rightIcon && <FontAwesome icon={rightIcon} />}
</button>
);
}
Though this solution is working I wonder if there is an easier way than having to check twice for an icon to be set. Also I would like to have the ability to use
instead of . Is there any way to escape the whitespace so I can write something like
{leftIcon && <FontAwesome icon={leftIcon} /> }
?
I tried {leftIcon && <FontAwesome icon={leftIcon} />{"&nsbp;"}}
or {leftIcon && <FontAwesome icon={leftIcon} />{&nsbp;}}
which leads to
TS1005: '}' expected.
This article suggests that
should work for intentional whitespace http://andrewhfarmer.com/how-whitespace-works-in-jsx/
Seeing as you should be able to insert
inline with other HTML I would have thought you don't need to wrap it up in brackets or a string. Imagine it just like writing <br />
and you should be able to glue it to the end of the <FontAwesome />
component.
render(): JSX.Element {
let { children, leftIcon, rightIcon } = this.props;
return (
<button>
{leftIcon && <FontAwesome icon={leftIcon} /> }
{children}
{rightIcon && <FontAwesome icon={rightIcon} />}
</button>
);
}
Disclaimer, this is untested
As an alternative, this github issue https://github.com/facebook/react/issues/1643 suggests you can add {' '}
for intentional whitespace, so I'd have thought this would work too:
render(): JSX.Element {
let { children, leftIcon, rightIcon } = this.props;
return (
<button>
{leftIcon && <FontAwesome icon={leftIcon} />{' '}}
{children}
{rightIcon && {' '}<FontAwesome icon={rightIcon} />}
</button>
);
}
Disclaimer, also untested
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.