I’m wondering if there’s a best practice way to reverse the ordering of child elements of some component conditionally, I do not want to override this using css.
My use case is for a button that can have an icon on one side or the other. What I have currently works:
const someFlag = true
return (
<div className="parent">
{someFlag && <img src='A'></img>}
<button>{"myButton"}</button>
{!someFlag && <img src='B'></img>}
</div>
)
but my actual child{X}
components are a bit more involved so I have some duplicate code, and I also want to guard against future cases where I might have more than 2 children.
I’m thinking of throwing this into an array and reversing based on the flag but I just have no idea what that means for performance, and am having trouble finding relevant results on google
2
Answers
You can make this element a separate component and just render it like you did. React is also about readability and your code is perfectly readable:
If your real code is really that simple, I suggest taking advantage of CSS flexbox if you can:
You can extract it into a CSS class as well:
Demo of how it would work: