Last active
August 15, 2023 01:37
-
-
Save Asraf2asif/50e1620f6a01232e22b20dc7704ea7ee to your computer and use it in GitHub Desktop.
Optimize redundant React-Bootstrap Tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
---------------From-------------------------- | |
<Row className='row-class'> | |
<Col sm={5} className='col1-class'> | |
<p>col 1</p> | |
</Col> | |
<Col sm={5} className='col2-class'> | |
<p>col 2</p> | |
</Col> | |
</Row> | |
---------------To-------------------------- | |
<RowCol className='row-class' colsProps={[ | |
{sm: 5, className: 'col1-class'}, | |
{sm: 5, className: 'col2-class'}, | |
]}> | |
<p>col 1</p> | |
<p>col 2</p> | |
</RowCol> | |
*/ | |
import { Row, Col } from 'react-bootstrap'; | |
function RowCol ({ children, colsProps = [null], ...otherProps }) { | |
return ( | |
<NestedTag | |
tag={{ parentTag: Row, childTag: Col }} | |
tagsProps={colsProps} | |
{...{ children, ...otherProps }} | |
/> | |
); | |
}; | |
function NestedTag ({ | |
tag: { parentTag: ParentTag, childTag: ChildTag }, | |
tagsProps = [null], | |
children, | |
...otherProps | |
}) { | |
if (!otherProps) { | |
otherProps = null; | |
} | |
return children ? ( | |
children.length > 1 ? ( | |
<ParentTag {...otherProps}> | |
{children.map((childElem, idx) => { | |
let elemProps = {}; | |
if (tagsProps[idx]) { | |
elemProps = tagsProps[idx]; | |
} | |
return ( | |
childElem && ( | |
<ChildTag key={idx} {...elemProps}> | |
{childElem} | |
</ChildTag> | |
) | |
); | |
})} | |
</ParentTag> | |
) : ( | |
<ParentTag {...otherProps}> | |
<ChildTag {...tagsProps[0]}>{children}</ChildTag> | |
</ParentTag> | |
) | |
) : null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks