Reputation: 687
I am trying to align icon in Button component. Passing iconAlign prop if it is right the icon will render first and text will later if left then vice versa. But I am getting this error by flow
React element `Icon`: 'object type'. See ./tmp/flow/flowlib_16523b66/react.js:159. This type cannot be coerced to 'string'.
Here is my component
<ButtonInner>
{
iconAlign === 'right' ? `${text} ${icon && <Icon color={iconColor} />}` :
`${icon && <Icon color={iconColor} />} ${text}`
}
</ButtonInner>
Am I missing something? Any better alternative please?
Upvotes: 0
Views: 1440
Reputation: 922
string literals finally convert everything to string. component's toString
is tracked by react and it throws error when toString
is called on a component. You can write the code as follows to achieve the same:
iconAlign === 'right' ? (
<Fragment> `${text} ` icon && <Icon color={iconColor} /> </Fragment>) : (
<Fragment> icon && <Icon color={iconColor} /> {` ${text}`} </Fragment>
)
If your are using react 16.2, you can user Fragment
to wrap the children. You can of course go old school and add a div
instead but that generates a lot of non-semantic divs in the generated html.
More about Fragments
here : https://reactjs.org/docs/fragments.html
Upvotes: 1
Reputation: 687
I should not have used the string literals to render my react component. I just wrapped it in a div and that worked
<ButtonInner>
{
iconAlign === 'right' ?
<div>{text} {icon && <Icon color={iconColor} /></div> :
<div>{icon && <Icon color={iconColor} />} {text}</div>
}
</ButtonInner>
This article helped https://reactjs.org/docs/conditional-rendering.html
Upvotes: 1