Open In App

Inline media query in React components

Improve
Improve
Like Article
Like
Save
Share
Report

Generally, one can not do inline styling with media queries because React doesn’t allow us to use media queries in inline styling. We can use radium which is a third-party package that enables media queries for inline styling.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

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

cd foldername

Project Structure: It will look like the following.

Project Structure

Step 3: Now create a new component Example.js in your src folder that will return the GeeksforGeeks text.

Step 4: Now go to the app.js file in your editor and edit it, so that it returns a component example(an example).

Step 5: Now install the Radium module from the root of your my-app using the command. 

$ npm install --save radium

Step 6: Import radium with { styleroot } from react in both app.js and example.js.

Step 7: Finally we can use media queries in our react component example.js. In this example, we have added a query if the width of the device is less than 501px then our app will display nothing.

Note: One thing we have to keep in mind that the syntax will be slightly different like we have to wrap everything which we are returning in styleroot.

Filename-App.js:

Javascript




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);


Filename-Example.js: Our Component

Javascript




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.



Last Updated : 21 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads