I have two almost identical components, Component A:
const ClaimedLabel = ():React.Element => (
<div tw="">
<p tw="">Some Text here</p>
<div tw="">
<Icon src="./icon.png" />
</div>
</div>)
Component B:
const ClaimedLabelPDF = ():React.Element => (
<View tw="">
<Text tw="">Some Text here</p>
<View tw="">
<Icon src="./icon.png" />
</View>
</View>)
tw - is tailwind style I ignored to improve code redability. As you can see those two components are identical but diferent tags were used, is it possible to write one single component to reuse it ? I have one idea to use isPDF flag, put two components into one and return component based on flag value, but in this case I still have duplicates:
const ClaimedLabel = (isPDF: boolean): React.Element => isPDF ? <View>...</View> : <div....</div>
CodePudding user response:
You could just create references to the Types of elements you need to swap.
const ClaimedLabel = (isPDF: boolean): React.Element => {
const RView = isPdf ? View : 'div';
const RText = isPdf ? Text : 'p';
return (
<RView tw="">
<RText tw="">Some Text here</p>
<RView tw="">
<Icon src="./icon.png" />
</RView>
</RView>
);
}