Home > other >  Change value of css in components
Change value of css in components

Time:05-19

I am new to React/Javascript and can't really solve this issue for a day.

I have object with names of players.

let players = {'Amber', 'Thomas', 'Trump', 'Michael', 'Someone'};

Basically players is the input function where users type their names and I store them here.

And I have a css for displaying them as a grid.

const styles = {
   section: {
     display: 'grid',
     gridGap: '5px',
     boxSizing: 'border-box',
     borderColor: 'black',
     padding: '5px',
     gridTemplateColumns: 'repeat(1, 1fr)',
}

I would like to change the value in 'repeat(value, 1fr)' when the length of players increases. In volleyball, there are six members in each team, so:

style = {list.length > 6 ? changeValueMoreSix : changeValueSixOrLess

I would like to separate them each six in case there are more players.

E.g. Case1: Just 5 player, it should display:

Player1
Player2
Player3
Player4
Player5

Case 2: 11 Players:

Player1   Player7
Player2.  Player8
Player3   Player9
Player4   Player10
Player5   Player11
Player6

Basic idea is to create a column if it exceeds more than 6, 12, 18, etc, or column = player.length / 6

CodePudding user response:

In case you want to calculate value based on length of the list in repeat(**value**, 1fr), you can use CSS values, attached in inline style of wrapper of list elements:

Calculate column amount (based on list length and 6 divider;

const columnAmount = Math.ceil(list.length / 6);

Then, use this value in your template:

<section 
   
  style={{ --column-amount: this.props.columnAmount }}
>
  <!-- list items  -->
</section>

And update your CSS:

const styles = {
   section: {
     display: 'grid',
     gridGap: '5px',
     boxSizing: 'border-box',
     borderColor: 'black',
     padding: '5px',
     gridTemplateColumns: 'repeat(var(--column-amount, 1), 1fr)',
}

where --column-amount in var(--column-amount, 1) is dynamic CSS value, 1 is callback value.

CodePudding user response:

You could create css classes for each required number (6, 12 etc):

.lessThanSix {
    gridTemplateColumns: 'repeat(1, 1fr)',
}

.moreThanSix {
    gridTemplateColumns: 'repeat(2, 1fr)',
}

And in js file conditionally change class of component, for example:

let currentClass = "";
list.length > 6 ? currentClass = moreThanSix : currentClass = lessThanSix;

Finally you'll get as more classes as many cases you have. You can change classes in switch/case block.

  • Related