How to isolate CSS from a component?

Asked

Viewed 298 times

2

I am using the React.js (in the example create React app) and I even created two components, but I could not isolate the .css of each component. The css of the tableInfo.css ends up being applied to the other components that have the same classes, that is to say it is being global. How can I isolate the tableInfo.css to be applied only to the component Tabulature?

According to my research it would be something like the Scoped CSS of Vue.js.

Table.js

import React from 'react';

import styles from './tabelaInfo.css';

export default class TabelaInfo extends React.Component {
 render() {
 return (
        <table>
            <thead>
                <tr>
                    <th>Nome</th>
                    <th>Tipo</th>
                    <th>Altura</th>
                    <th>Peso</th>
                </tr>
            </thead>

            <tbody>
                <tr>
                    <td>Bulbasauro</td>
                    <td>Planta</td>
                    <td>2</td>
                    <td>100kg</td>
                </tr>
            </tbody>
        </table>
    )
 }
}

tableInfo.css

table{
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;
}
table tr th{
    background-color: #f1f1f1;
    border: 1px solid #dadada;
    height: 30px;
    padding-left: 10px;
    font-size:15px;
    color: #333333;
    font-weight: 500;
    padding-top: 6px;
    text-align: left;
}
table tr td{
    border: 1px solid #dadada;
    height: 30px;
    padding-left: 10px;
    font-weight: normal;
    font-size: 15px;
    padding-top: 6px;
}
  • The element ends up returning "Tableinfo" as a class of each element?

1 answer

1

One of the solutions proposed by the React documentation is the use of inline styles.

Em React, inline styles are defined as an object JavaScript, whereas:

  • To key is the version in camelCase of the style name (i.e. backgroundColor)
  • The value is the value of the style, usually a string (i and.. '#FFF')

That way, your case would look more or less like this (function only render):

render() {
  const style = {
    width: '100%';
    tableLayout: 'fixed';
    borderCollapse: 'collapse';
    // Demais propriedades
  };

  return (
    <table style={style}>
      <thead>
        <tr>
          <th>Nome</th>
          <th>Tipo</th>
          <th>Altura</th>
          <th>Peso</th>
        </tr>
      </thead>

      <tbody>
        <tr>
          <td>Bulbasauro</td>
          <td>Planta</td>
          <td>2</td>
          <td>100kg</td>
        </tr>
      </tbody>
    </table>
  )
}

You can read a discussion about good practices of using the inline style in React here (in English).

  • interesting, I got to see also a little CSS Modules, but I could not get to something like scoped css from Vue.js

Browser other questions tagged

You are not signed in. Login or sign up in order to post.