Tags
react.js
Asked 2 years ago
9 Jul 2021
Views 250
Joanny

Joanny posted

Best way to write media query in reactJS

Best way to write media query in reactJS
noob

noob
answered Feb 28 '23 00:00

The best way to write media queries in ReactJS is by using CSS-in-JS libraries such as styled-components or emotion. These libraries allow you to write CSS code directly in your React components using JavaScript. Here's an example of how to write media queries using styled-components:


import styled from 'styled-components';

const Container = styled.div`
  background-color: #fff;
  padding: 20px;

  @media (min-width: 768px) {
    padding: 40px;
  }
`;

function MyComponent() {
  return (
    <Container>
      <h1>ArrayOverflow</h1>
    </Container>
  );
}


In this example, we define a styled component called Container using the styled function from the styled-components library. We set the background color and padding of the component using regular CSS properties. We then use a media query with the @media rule to change the padding of the component when the screen width is at least 768 pixels. This allows us to create responsive layouts that adapt to different screen sizes.

By using CSS-in-JS libraries like styled-components, we can write clean and modular code that combines the power of CSS with the flexibility of JavaScript.
Post Answer