How to isolate the CSS of a component?

2

I'm using react.js (in the example the create react app) and I even created two components, but I could not isolate the .css of each component. The css of the Info.css table ends up being applied to the other components that have the same classes, ie it is global . How can I isolate the TableInfo.css to be applied only in the TableInfo

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

TableInfo.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;
}
    
asked by anonymous 31.05.2017 / 02:16

1 answer

1

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

In React, inline styles are defined as a JavaScript object, where:

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

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

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 of good practices in using inline style in React here .

    
31.05.2017 / 03:43