Skip to content

Instantly share code, notes, and snippets.

@Asraf2asif
Last active August 15, 2023 01:37
Show Gist options
  • Save Asraf2asif/50e1620f6a01232e22b20dc7704ea7ee to your computer and use it in GitHub Desktop.
Save Asraf2asif/50e1620f6a01232e22b20dc7704ea7ee to your computer and use it in GitHub Desktop.
Optimize redundant React-Bootstrap Tag
/*
---------------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;
};
@Asraf2asif
Copy link
Author

Helpful

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment