I have been exploring a quick and easy way to add Media queries in React using styles and a simple wrapper component.
The problem I found with these solutions were the lack of browser support. So I explored using CSS and Wrapper Components to do something similar.
The solution is quite simple and might be helpful if you are exploring media queries and React.
So lets dive in, first we need to create a component.
This component behaves as a wrapper component for child components.
When using this component you pass the size (defined by you, in our example mobile and desktop) you want your child components to render in. These are defined in your
You can add any size you like on the
propTypes as long as you write the matching class names in your css (we will see more of this later).
As you can see in our example we have two sizes defined
desktop. When the component renders it will wrap our children with a class of
MediaQuery-desktop class name.
Now all we have to do is write some css to match the class names. So lets take a look at that.
Adding media queries
This part is initially up to you.
This file just supports our examples we made in our
As you can see we have
desktop media query support. You can add any media query you like, just make sure you match the class name up to your
propTypes in your
Now lets use our component in action.
Using the component
That’s all have to do.
The header ‘Mobile View’ will get rendered on mobile.
The header ‘Desktop View’ will get rendered on desktop.
This was just a quick experiment I come up with when exploring Media queries in React. I haven’t created a demo as its super easy to copy this code and try it out for yourself.
You can checkout the whole gist below.
If you have any questions just tweet me, or leave a comment.
Sign up for the latest articles!
Get the latest posts straight to your inbox!Sign up