skip to Main Content

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


  1. 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:

    return (
      <div className="parent">
        {someFlag && <MyComponent />}
        <button>{"myButton"}</button>
        {!someFlag && <MyComponent />}
      </div>
    )
    
    Login or Signup to reply.
  2. If your real code is really that simple, I suggest taking advantage of CSS flexbox if you can:

    <div className="parent" style={{ display: "flex", flexDirection: someFlag ? "column" : "column-reverse" }}>
      <img src='A' />
      <button>{"myButton"}</button>
      <img src='B' />
    </div>
    

    You can extract it into a CSS class as well:

    .parent {
        display: flex;
        flex-direction: column;
    }
    
    .parent.reversed {
        flex-direction: column-reverse;
    }
    
    <div className={`parent ${someFlag ? "" : "reversed"}`}>
      <img src='A' />
      <button>{"myButton"}</button>
      <img src='B' />
    </div>
    

    Demo of how it would work:

    .parent {
        display: flex;
        flex-direction: column;
    }
    
    .reversed {
        flex-direction: column-reverse;
    }
    <div class="parent">
        <p>child 1</p>
        <p>middle</p>
        <p>child 2</p>
    </div>
    
    <hr />
    
    <div class="parent reversed">
        <p>child 1</p>
        <p>middle</p>
        <p>child 2</p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search