Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the order of Components in React depending on a variable?

I have a React Component which is rendered by this map function:

<div className="links-container">
    {links.map((link, i) => (
        <Links
            key={link.text}
            icon={link.icon}
            text={link.text}
            isRight={i % 2 === 0 ? true : false}
        />
    ))}
</div>
import React, { Component } from "react";

export default class Links extends Component {
    render() {
        const { icon, text, isRight } = this.props;
        return (
            <div style={{ alignSelf: isRight ? "flex-end" : "" }}>
                <div className="link">
                    <img
                        className="link-img"
                        src={icon}
                        alt="link"
                        style={{ borderColor: isRight ? "#1689FC" : "#FD003A" }}
                    />
                    <div className="link-text">{text}</div>
                </div>
            </div>
        );
    }
}

And what I want to do is, if the isRight is true, I want to render the text first and then the img, if isRight is false, I want to render the image and then the text. Now, I am aware that I could wrap this thing in a big if statement like this:

isRight ? <div><text/><img/></div> :  <div><img/><text/></div>

But I am wondering if there's a better way to do this because my approach uses repetitive code, which is the reason why I have this Links Component in the first place.

like image 714
randomboiguyhere Avatar asked Mar 04 '23 00:03

randomboiguyhere


1 Answers

You can use display:flex and flex-direction property on <div className="link">

flex-direction: row-reverse or flex-direction: column-reverse depending on your layout.

like image 53
Anurag Srivastava Avatar answered Mar 05 '23 16:03

Anurag Srivastava