Open In App

Inline media query in React Components

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Inline media query in React components is generally not possible because React doesn’t allow us to use media queries in inline styling. But it can be done with the help of external libraries and packages.

Approach

To use inline media query in React components we will be using radium npm package. Radium allows us to apply media query using inline styling in React. Radium also provides advanced features like keyframes and pseudo-selectors.

Step to Create React App and Install Module

Step 1: Initialize React Project

Create a React application using the following command:

npx create-react-app foldername

Step 2: Switch to the Project Directory

After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Step 3: Install Radium

npm i radium

Project Structure:

project-structure---inline-media-query-react

Project Structure

The updated dependencies in package.json file are:

  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "radium": "^0.26.2",   
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-scripts": "5.0.0",
    "web-vitals": "^1.0.1"
  },

Example: This example uses Radium and StyleRoot components from radium package to implement inline media query in React components.

JavaScript
// Filename - App.js

import React, { Component } from "react";
import Radium, { StyleRoot } from "radium";

// Importing our Example component(src folder)
import Example from "./Example";

class App extends Component {
	render() {
		return (
			// Wrapping in styleroot
			<StyleRoot>
				<div className="App">
					<Example />
				</div>
			</StyleRoot>
		);
	}
}

export default Radium(App);
JavaScript
// Filename - Example.js

import React, { Component } from "react";
import Radium, { StyleRoot } from "radium";
class App extends Component {
	render() {
		const style = {
			// Adding media query..
			"@media (max-width: 500px)": {
				display: "none"
			}
		};
		return (
			// Wrapping under styleroot.
			<StyleRoot>
				<div className="App">
					<h1 style={style}>GeeksforGeeks</h1>
				</div>
			</StyleRoot>
		);
	}
}

export default Radium(App);

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: You will see the following output on your browser screen:

Now inspect the window and decrease the width up to 501px, the GeeksforGeeks will not be visible now, this is how you can use media queries inline in the React app.



Next Article

Similar Reads