I have wrapper component which in some cases I need to reorder the position of only one of the children on it, sometimes I require to have ComponentX at the top, sometimes at the bottom. Is there any elegant way to achieve this? because I did it but replicating code.
const ComponentX = () => <h4>component x</h4>
const Component1 = () => <h4>component 1</h4>
const Component2 = () => <h4>component 2</h4>
const ComponentWrapper = ({xOnTop = false}) => {
return (
<div className="box">
<h1>My components</h1>
{xOnTop && <ComponentX />}
<Component1 />
<Component2 />
{!xOnTop && <ComponentX />}
</div>
)
}
Here's my codepen
What you have is perfectly fine, but I tried to come up with a different way to go about it and came up with this. So you can easily just invert the order of the component's keys using the xOnTop parameter.
const components = [
<h4 key="1">component x</h4>,
<h4 key="2">component 1</h4>,
<h4 key="2">component 2</h4>
]
const ComponentWrapper = ({xOnTop = true}) => {
components.sort((a, b) => xOnTop ? a.key - b.key : b.key - a.key)
return (
<div className="box">
<h1>My components</h1>
{components.map(c => c)}
</div>
)
}