Home > Software design >  Modify css Property in react
Modify css Property in react

Time:02-13

Hi I'm creating a dynamic table component using css grid. But I want to modify the grid-template-columns css property. I know how to do it in css. I'm using repeat to do this. But I want to modify the repeat value every time I use the component in react. For example if I need a table with 5 columns y use repeat(5, 1fr) and if I want to create a 3 column table I use repeat(3, 1fr).

<div className="xx-table">
    <div className="xx-table-header">
        <div className="xx-table-row">
            <div className="xx-table-data">Title1</div>
            <div className="xx-table-data">Title2</div>
            <div className="xx-table-data">Title3</div>
            <div className="xx-table-data">Title4</div>
            <div className="xx-table-data">Title5</div>
        </div>
    </div>
    <div className="xx-table-body">
        <div className="xx-table-row">
            <div className="xx-table-data">Data1</div>
            <div className="xx-table-data">Data2</div>
            <div className="xx-table-data">Data3</div>
            <div className="xx-table-data">Data4</div>
            <div className="xx-table-data">Data5</div>
        </div>
        <div className="xx-table-row">
            <div className="xx-table-data">Data6</div>
            <div className="xx-table-data">Data7</div>
            <div className="xx-table-data">Data8</div>
            <div className="xx-table-data">Data9</div>
            <div className="xx-table-data">Data10</div>
        </div>
    </div>
</div>

And the css

xx-table-row {
    display: grid;
    grid-template-columns: repeat(5, minmax(100px, 1fr));
}

I can´t figure it out how to do this. I don´t know if inline style is the way or any other method that I don´t know

CodePudding user response:

You should look into styled-components.

Through styled-components, you could set the number of columns as a prop to dynamically choose its value every time you use the component (and from what I know it also helps in terms of performance).

The code would look like this:

import styled from 'styled-components'

const StyledRow = styled.div`
  display: grid;
  grid-template-columns: ${props => `repeat(${props.columns}, minmax(100px, 1fr))`};
`

// in the component
<StyledRow columns={5}>
    // ideally, style these with styled-components as well
    <div className="xx-table-data">Data1</div>
    <div className="xx-table-data">Data2</div>
    <div className="xx-table-data">Data3</div>
    <div className="xx-table-data">Data4</div>
    <div className="xx-table-data">Data5</div>
</StyledRow>
  • Related