Home > OS >  How to create a reusable component with many possibilities based on the screen size?
How to create a reusable component with many possibilities based on the screen size?

Time:09-04

I'm making a blog website with a UI similar to enter image description here

horizontal:

enter image description here

vertical:

enter image description here

I can't find any pattern between these possibilities. My workaround is to pass a layout object to the component that defines the way it should look in different screen sizes. something like this:

const layout = {
  mobile: "float",
  tablet: "horizontal",
  desktop: "horizontal"
}

And I add different classes based on the layout object:

<div class={classnames(
        layout.mobile === "float" && "mobile:relative",
        layout.tablet === "float" && "tablet:relative",
        layout.desktop === "float" && "desktop:relative",

        layout.mobile === "horizontal" && "mobile:flex",
        layout.tablet === "horizontal" && "tablet:flex",
        layout.desktop === "horizontal" && "desktop:flex",

        layout.mobile === "vertical" && "mobile:flex mobile:flex-col",
        layout.tablet === "vertical" && "tablet:flex tablet:flex-col",
        layout.desktop === "vertical" && "desktop:flex desktop:flex-col",

     )}>
</div>

BTW this is JSX syntax with tailwindcss classes.

As you can see, it's very messy and it gets worst as the complexity grows:

  1. What if I want the image to be in a square shape when the layout is not "float"?
  2. What if I want to add something to the card, like an icon, but it should be in the corner for "horizontal" and "vertical" layouts and in the center for the "float" layout?

And so on.

So I like to hear your take on this. I don't want you to do my homework, I just need some ideas. Anything could be helpful. Maybe a design pattern that I don't know?

CodePudding user response:

The areas are in my opinion still logically divided and each area can be given a unique css class.

eg top most slider can be ticker and the unique behavior is, the layout of each card doesn't change

the middle area with 5 cards can be featured and the unique behaviour is, except slider, all other cards change the layout at the different viewport, eg desktop and tablet = float and for mobile = horizontal

Similarly, the rest of the rules can be created based on the context.

It's hard to generalise and hence easy to hard code the configuration.

I am not a tailwind expert so can't give you an equivalent code. Hope you got my point.

  • Related