top of page
Logo der Online Agentur mdwp

CSS in JS

CSS in JS is a term used in the React JS universe that describes a technique or pattern where CSS is composed in JavaScript. This allows developers to write CSS that is tied specifically to their components. The aim is to bring the benefits of locally scoped CSS to each component and eliminate common problems with CSS, such as global namespace, dependencies, dead code elimination, and minification.

Typically, when developers style a website, they'll create separate CSS files that link to HTML. With CSS in JS technique, you instead write your CSS directly within JavaScript code. By doing this you can manage all aspects of a component, including its styles, within one file.

Here's a basic example of how one might write CSS in JS using the styled-components library:

```javascript
import styled from 'styled-components'

const Button = styled.button`
background-color: blue;
color: white;
font-size: 16px;
padding: 10px;
`

// Use it like any other React component
render(<Button>Hello World</Button>)
```

The declared "Button" constant is a React component with styles attached to it. Now, these styles are part of the JavaScript component, instead of being located in a separate stylesheet.

bottom of page