Dino Geek, try to help you

How to do style encapsulation in Reactjs?


In ReactJs, there are several ways to do style encapsulation:

1. Inline Styles:

React recommends using inline styles, which are written as attributes in JavaScript objects. Unlike CSS, hyphens are not allowed in object keys, so you should use camelCase instead.

Example:

``` import React, { Component } from ‘react’;

class Example extends Component { render() { var divStyle = { color: ‘white’, backgroundColor: ‘DodgerBlue‘ }; return
{this.props.text}
} } export default Example; ```

1. CSS Modules

CSS Modules allow you to write styles in CSS files but consume them as JavaScript objects for style encapsulation.

To use CSS modules, when importing your CSS file, prefix your import statement with `:local`.

``` import styles from ‘./Example.css’;

function Example() { return
Hello, world!
} ```

And CSS file should look like this:

```
.example { background-color: black; color: white;
}
```

1. Styled-Components

You can use the `styled-components` library to generate and apply classes directly in your components.

``` import styled from ‘styled-components’;

const Button = styled.button` background-color: blue; color: white; `; function Example() { return } ```

In this example, a new component `Button` gets created with the given styles.

1. CSS in JavaScript (External Libraries)

Libraries such as `aphrodite`, `glamor`, `jss`, etc, provide a way to write CSS in JavaScript which allows styles to be a part of the component and gets rendered only when that particular component is included.

Example with `aphrodite`:

``` import {StyleSheet, css} from ‘aphrodite’;

const styles = StyleSheet.create({ red: { backgroundColor: ‘red‘ }, blue: { backgroundColor: ‘blue‘ }, hover: { ‘:hover’: { backgroundColor: ‘red‘ } }, }); class App extends React.Component { render() { return
Hello!
} } ```

These are some of the popular approaches to style encapsulation in ReactJS. Depending on how you structure your project, there may be other methods that are more suitable.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use