skip to Main Content

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


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

    Login or Signup to reply.
  2. I recommend react-use for getting a CSS media query.

    import {useMedia} from 'react-use';
    
    const App = () => {
      const isWide = useMedia('(min-width: 600px)');
    
      const content = isWide ? (
        <DataTable columns={columns} data={data} />
      ) : (
        <p>insert cards here...</p>
      )
    
      return (
        <>
          {/* YOUR CODE */}
          {content}
        </>
      );
    };
    

    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.

    const content = (
      <>
        <div className='hidden sm:block'>
          <DataTable columns={columns} data={data} />
        </div>
        <div className='block sm:hidden'>
          <p>insert cards here...</p>
        </div>
      </>
    )
    

    Before adding above, you need to override default screen breakpoints at tailwind.config.js.

    module.exports = {
      theme: {
        screens: {
          'sm': '640px',
          // => @media (min-width: 600px) { ... }
        }
      }
    }
    

    Take a look at here. Configuring custom screens

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search