Top 5 amazing way to use inline style in React js

  • react-js
  • 107 Views
  • 4 Min Read
  • 6 May 2024

Hey there, developers! Welcome to this guide. Inline CSS can be super handy in certain situations, especially when you need to make quick design tweaks without dealing with separate files. But did you know that you can use external CSS files as well as inline styles in a React project? Don't worry, I'll walk you through it in this article.

 

I'll reveal the top 5 amazing techniques for using inline CSS in your React.js projects.

 

The way of the inline style:

 

  1. Using Inline Styles with the style Attribute:
  2. Using Inline Styles with object variable:
  3. Applying Inline Styles Conditionally Based on State or Props:
  4. Extending Inline Styles with Pseudo-selectors and Media Queries using the Radium tool:
  5. Utilizing CSS Modules for Scoped Styling:
 
 

1. Using Inline Styles with the style Attribute:

 
When using inline CSS in HTML, we typically apply styles directly within the style attribute of an element, like this: <h1 style="color: red">Hello, World!</h1>. However, in React JSX, there are a few differences:
 
  • Inline styles in JSX are written as JavaScript objects within double curly braces ({{ }}).
  • CSS property names are written in camelCase instead of kebab-case.
  • Property values are provided as strings.
 
Here's how it looks in React JSX:
 
import React from 'react';

function App() {
    return (
        <div style={{ height: '100vh', display: 'grid', placeItems: 'center', }}>
            <h1 style={{ color: 'red' }}>Hello, World!</h1>
        </div>
    );
}

export default App;
 
Inline Style in React JS
 
In this code, we're using double curly braces ({{ }}) to denote an inline CSS object within JSX. This allows us to embed CSS directly into our JSX code.
 
CSS property is written in camelCase, which is the JavaScript convention. For example, placeItems instead of place-items.
 
Property values are provided as strings. For instance, '100vh' for the height property and 'grid' for the display property.
 

2. Using Inline Styles with object variable:

 
import React from 'react';

function App() {
    const styleDiv = {
        height: '100vh',
        display: 'grid',
        placeItems: 'center'
    }

    const styleHeading = {
        color: 'steelblue'
    }

    return (
        <div style={styleDiv}>
            <h1 style={styleHeading}>Hello, World!</h1>
        </div>
    );
}

export default App;
 
Inline Style in React
 
In this code, we've defined two JavaScript objects, styleDiv, and styleHeading, containing CSS properties and values.
 
The styleDiv configures properties for <div> element, including height, display, and placeItems. And the styleHeading sets the color property to red for a heading.
 
 

3. Applying Inline Styles Conditionally Based:

 
import React from 'react';

function App({ isSpecial }) {
    return (
        <div>
            <h1 style={{
                color: isSpecial ? 'red' : 'green',
                fontSize: isSpecial ? '24px' : '20px',
                fontWeight: isSpecial ? 'normal' : 'bold'
            }}>Hello, World!</h1>
        </div>
    );
}

export default App;
 
Inline Style in React
 
In JSX, we can define inline CSS directly using double curly braces {{ }}. Within these braces, we set CSS properties and values directly. This allows us to conditionally style elements based on props, as demonstrated in the example. 
 
 

4. Extending Inline Styles with Pseudo-selectors and Media Queries using the Radium tool:

 
In React, you can nest styles within a styles object and apply them using pseudo-classes like :hover. However, it's important to note that inline styles in React don't directly support pseudo-selectors like :hover.
 
To achieve inline :hover functionality, you'll need to install a library like Radium. You can install the Radium tool by using the following command:
 
npm i radium

// If installation fails, try this command 👇
npm install--save radium--force
 
Radium extends React's inline styling capabilities, allowing for pseudo-class and media query usage directly within inline styles.
 
import React from 'react';
import Radium from 'radium';

const styles = {
    parentEl: {
        height: '100vh',
        display: "grid",
        placeItems: "center",
    },
    childEl: {
        color: "red",
        transition: 'color 0.3s', // Adding transition for smooth color change
        ':hover': { // Applying hover effect
            color: 'green',
        }
    }
}

function App() {
    return (
        <div style={styles.parentEl}>
            <h1 style={styles.childEl}>Hello, World!</h1>
        </div>
    );
};

export default Radium(App);
 
Inline style in React
 
Importing Radium: We've imported Radium to utilize its inline styling features.
 
Defining Styles: Two JavaScript objects, styles.parentEl and styles.childEl, encapsulate CSS properties.
 
Applying Styles: Using the style attribute in JSX, we apply these styles to respective elements.
 
Radium Wrapper: The App component is wrapped with the Radium higher-order component, enabling the usage of Radium's capabilities for handling inline styles and pseudo-class selectors like :hover.
 
You can also write code for the media queue using Radium, but you can use it only when you have to work on a small project where not much code is required.
 
 

5. Utilizing CSS Modules for Scoped Styling:

 
// styles.module.css file
.myClass {
    color: red;
    font - size: 20px;
}

// App.js file
import React from 'react';
import styles from './styles.module.css';

function App() {
    return (
        <div className={styles.myClass}>
            Hello, World!
        </div>
    );
}

export default App;
 
Defining Inline Styles: The CSS styles are defined in a separate file named styles.module.css. Inside, we define the .myClass class with properties like color set to red and font-size to 20 pixels.
 
Importing Styles: In the App.js file, we import the CSS module using import styles from './styles.module.css';. This allows us to access the CSS class names via the styles object.
 
Applying Styles: Within the App function, we apply the styles to the JSX element using the className attribute. By specifying className={styles.myClass}, we associate the styles defined in .myClass with the <div> element.
 

This way you can write inline CSS within your React component. In this way, we can write CSS styles separately from the component logic.

 
 

Conclusion

 

To become a developer like a senior, you need to know such tricks. We've told you everything from this article to adjusting styles based on state or props with the style attribute and even extending inline styles with pseudo selectors using tools like Radium. Start practicing now to enhance your skills.

 

For bigger projects, it's best to use a separate CSS file rather than just inline styles. But still, if you prefer using inline styles, even for bigger projects, then you can use Tailwind CSS, which is easy to use even for large-scale projects.

 

If you have any questions regarding this article or any other web development, you can ask them in the question box given below, and you will get an answer as soon as possible.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Diya Jain ( diya )

The Dev without a Degree

Joined On 10 Apr 2024

More from Diya Jain

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....

Top Strategies for Search Bar Optimization on Major Platforms

web-development

6 Sep 2024

Discover top strategies for search bar optimization on major platforms. Enhance real-time ....

Top Strategies to Optimize ReactJS Application Performance for Faster Load Times

react-js

23 Aug 2024

From this article, you will discover the best practices to enhance the speed of loading yo....

Comprehensive Guide to Tooltips in ReactJS

react-js

5 Jun 2024

Explore ReactJS tooltips from start to finish! Learn how to add, customize, troubleshoot, ....

Comprehensive Guide to React Hooks: When and How to Use Each Hook Effectively

react-js

9 Jul 2024

In React, we use a component-based structure. A component is like a building block of code....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....