You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
22 Hrs
13 Min
27 Seg

Qué es CSS-in-JS

17/28
Resources

What is CSS in JS and why doesn't it replace regular CSS?

CSS in JS is an innovative way of writing CSS styles using JavaScript. While many may question whether this approach could ever replace traditional CSS, the categorical answer is no. CSS in JS ultimately generates normal CSS; however, the way we write it and integrate it with the component logic of an application is different. By using CSS in JS, we can enhance the benefits of working with components in our application, taking full advantage of JavaScript's functionality to create dynamic and efficient styles.

How do we integrate CSS in JS into our projects?

Historically, the standard approach has been to create .css style sheets and link them to our HTML documents. Alternatively, we can also employ inline styles or the use of <style> tags. However, the trend has evolved, integrating preprocessors and postprocessors for even more efficiency.

  • Preprocessors such as Sass or Less facilitate the use of variables, functions and other programmatic elements in CSS style.
  • Postprocessors such as PostCSS allow us to use future CSS features, ensuring that the browser understands them immediately.

With the rise of components, applications are being broken down into smaller parts, making them easier to maintain and expand with new functionality. CSS in JS integrates styles directly within components, adding not only organization but also the potential of JavaScript to create more complex and dynamic styles.

How do we implement CSS in JS with Style Components in React?

Let's look at an example using Style Components, a popular way of working with CSS in JS within the React ecosystem. Here we define a component called Title:

`import styled from 'styled-components';
const Title = styled.h2`
 color: white; font-size: 60px; `;

This syntax is familiar from normal CSS. The big difference is that we specify that when we want to apply certain styles, we use the Title component instead of defining styles for all <h2> in the application.

How do we make use of CSS dynamics in JS?

Implementing CSS dynamics in JS is simple. Suppose we want to change the color of the title depending on whether there is an error:

const Title = styled.h2`
 color: ${(props) => (props.error ? 'red' : 'white')}; `;

When we use the Title component and pass the error attribute, the color will change to red. Otherwise, it will be white. This is just a sample of how we can apply JavaScript logic to our styles, taking advantage of props and the context of entire applications.

How to handle global CSS styles in JS?

A common myth is that CSS in JS does not allow writing global styles. However, CSS in JS tools such as Style Components enable the creation of global styles for general tags, certain class selectors, or basic elements such as the body. This ensures that, even using CSS in JS, we can maintain the need to apply styles to application-wide elements without complications.

As you can see, CSS in JS not only keeps the essence of traditional CSS alive, but expands its horizons by integrating the programmatic capabilities of JavaScript to provide a more robust development experience. This approach is ideal when working with modern frameworks and components, favoring a more customizable and dynamic set of styling features. Get your code editor ready and delve into the classes in this module to explore the possible applications of this knowledge - continue to learn and revolutionize your development experience!

Contributions 13

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

17.-¿Qué es CSS-in-JS?

Es literalmente escribir CSS desde JS y no, no reemplaza a los estilos normales ya que al final CSS-in-JS genera un CSS normal, la diferencia esta en como lo escribimos cuando estamos desarrollando la aplicación y como aumenta la ventaja de trabajar con componentes.

También tenemos a los preprocesadores y postprocesadores de CSS que nos dejan escribir CSS de manera más sencilla usando variables, ciclos, mixins, filtros, funcione, etc. Los postprocesadores nos permiten usar las funcionalidades que CSS “tendrá” en el futuro y nos dejan usarlas desde ya, también compilan a CSS normal.

Componentes y CSS-in-JS

Logramos que no solo la estructura HTML y lógica en JS de cada componente este dentro de componentes, también logramos que el CSS este dentro del componente.

Otra ventaja es que podemos usar JS para programar nuestros estilos y hacerlos dinámicos.

“Los estilos globales no son una desventaja en CSS-in-JS”

CSS-In-Js es la forma de escribir CSS desde JS. Estos no reemplazan los estilos normales, después de todo CSS-In-JS se convierten en estilos normales.

La forma de trabajar en CSS es escribiendo Hojas de estilo y linkeando este a nuestra pagina HTML. Pero también tenemos a los preprocesadores que nos dejan programar de una forma mas agradable el CSS y esto lo compilan a código CSS normal.

Con CSS-in-Js nos ayuda que la estructura sea mas sencilla con mejor organización para así poder ordenar todo entre componentes, al igual que con JS podemos hacer estilos dinámicos.

Podemos utilizar funciones para condicionar algunos estilos dentro de esto, al igual que hacer condiciones dependiendo del contexto de la aplicación.

Los estilos globales no son una desventaja de CSS-in-Js

En lo personal me gusta la manera en como NextJS ha implementado styled-jsx, una manera bastante similar a styled components.

Aqui les dejo un pequeño articulo que profundiza a detalle Css in Js:
https://webdesign.tutsplus.com/es/articles/an-introduction-to-css-in-js-examples-pros-and-cons--cms-33574

easy peace!!!

Desde Wikipedia.

En español podemos encontrar que template literals, también llamado acento inverso, tilde griega. Podemos decir que es el simbólo prima, Usado para marcar segundos.

Cómo sea que la conozcan, cuidensé de ella y confundirla por apóstrofo (comilla simple)

Acento agudo (en negro) sobre «I» mayúscula; apóstrofo (en verde); comilla simple recta (en rojo); prima (en azul); acento agudo (en negro) sobre «i» minúscula; en los tipos de letra Arial, Calibri, Tahoma, Times New Roman y Linux Libertine.

Al principio tenía mis dudas, pero viendolo así me parece genial porque nos ordena mucho el codigo

CSS-in-JS me parece interesante la forma que se puede escribir código CSS desde JavaScript para trabajar con componentes

CSS-in-JS

Es escribir CSS con JavaScript
.
Nos ayuda que la estructura sea mas sencilla con mejor organización para así poder ordenar todo entre componentes, al igual que con JS podemos hacer estilos dinámicos.

AMEEEEEEEENNN

Yo siempre tenia conocimiento de que existe SASS pero seguramente es muy avanzado integrarlo en JavaScript, deberiamos probarlo muy pronto.