I’m trying to display a layout for a page that’s dependent on it being the width of a phone. If it’s screen width, I want to display cards else, a table. Does anyone know how to do this using tailwind’s breakpoints? Until now I’ve been using window.innerwidth, but it’s not working and I think it’s a bad approach.
Here’s what I have:
if (window.innerWidth > 600) {
content = <DataTable columns={columns} data={data} />;
} else {
console.log(window.innerWidth);
content = <p>insert cards here...</p>;
}
And then ofc, I’m rendering content like so:
<>
<div className="text-[35px] text-neutral-900">
Welcome back,{" "}
<span className="font-semibold text-[50px] text-black">
{currentUser.name}
</span>
</div>
<div className="text-[25px] text-zinc-400 font-extralight">
Here are your reminders...
</div>
{content}
</>
I was thinking making the the cards invisible until it reaches a breakpoint, so rendering both, but that also doesn’t seem like a good idea.
2
Answers
Yes tailwind has breakpoints same as CSS media queries.
But the tailwind breakpoints are pre-defined eg: sm is 640px you can have a look at all breakpoints and their values in their docs here. You can Override the defaults as mentioined in this section
Also I saw you are using arbitrary values like
text-[35px]
. Tailwind encourages everyone to use their pre-defined values eg:text-4xl
. This is done to maintain UI consistency.I recommend react-use for getting a CSS media query.
You can get more idea from its documentation
If you don’t like this hook, then there is no other way than rendering both elements.
Before adding above, you need to override default screen breakpoints at tailwind.config.js.
Take a look at here. Configuring custom screens