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‘ }; return1. 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() { returnAnd 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() { returnThese 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.