Search code examples
cssreactjsjsxag-gridag-grid-react

React how to avoid css overide other components?


i am trying to create React aplication which uses AG-Grid table. Previously I customized table and removed borders of the ag grid by overiding css. I used this code to do so.

.ag-root-wrapper {
    border: solid 0px !important;
    border-color: var(--ag-border-color, white) !important;
}

But i noticed that code which i used only for one component has influenced whole aplication. I was curious maybe is there way to locally import css only for specific component? This is the way i was importing css for component

import './Statistics.css'
import { AgGridColumn, AgGridReact } from 'ag-grid-react';

const Statistics = () => {
    return (
    <div className='content'>
     <div className='content-left'>
      <div className="ag-theme-alpine">
        <AgGridReact
           rowData={data}
            style={{borderColor: 'red'}}
            rowSelection="single"
            filter={false}
        >
         <AgGridColumn
          headerName="Date"
          field="date"
          resizable={true}
          filter={false}
          width={130}
          flex={1}
          sort={'asc'}
          cellStyle={{fontSize: '1vw'}}
         />
       </AgGridReact>
      </div>
     </div> 
    </div>
     )}

export default Content;

Solution

  • When you use pure css or css preprocessors (Sass, less..), the imported css will always be global to your app. It is really useful to scope every component in a unique classname so you can scope css.

    import './Statistics.css'
    import { AgGridColumn, AgGridReact } from 'ag-grid-react';
    
    const Statistics = () => {
        return (
    +   <div className='root-statistics'>
        <div className='content'>
         <div className='content-left'>
          <div className="ag-theme-alpine">
            <AgGridReact
               rowData={data}
                style={{borderColor: 'red'}}
                rowSelection="single"
                filter={false}
            >
             <AgGridColumn
              headerName="Date"
              field="date"
              resizable={true}
              filter={false}
              width={130}
              flex={1}
              sort={'asc'}
              cellStyle={{fontSize: '1vw'}}
             />
           </AgGridReact>
          </div>
         </div> 
        </div>
    +   </div>
         )}
    
    export default Content;
    
    .root-statistics .ag-root-wrapper {
        border: solid 0px !important;
        border-color: var(--ag-border-color, white) !important;
    }