Search code examples
reactjsmaterial-uistyled-components

react material-ui styled-components


I have built an app which shows orders that are fetched from my api. orders have some properties as shown here:

id(pin): 22
open(pin): "3.60000000"
high(pin): "4.50000000"
low(pin): "3.20000000"
close(pin): "4.10000000"
time(pin): "2022-07-30T15:12:00+04:30"
active(pin): false
staged(pin): "OFFTRACK"

and I use styled components to show these as follow:

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  '&:nth-of-type(odd)': {
    backgroundColor: theme.palette.action.hover,
  },
  // hide last border
  '&:last-child td, &:last-child th': {
    border: 0,
  },
}));

actually my orders has three different values in respect to staged property of the order; namely: ontrack, offtrack and staged. I wanted to apply this logic in a way those StyledTableRows could have different styles according to the staged property.

and the part I placed the component:

{orders.map((order, index) => {
  return (
    <StyledTableRow key={index}>
      <StyledTableCell align="center">{order.open}</StyledTableCell>
      <StyledTableCell align="center">{order.high}</StyledTableCell>
      <StyledTableCell align="center">{order.low}</StyledTableCell>
      <StyledTableCell align="center">{order.close}</StyledTableCell>
    </StyledTableRow>
  )
})}

I'm not that new to @mui but about styled components totally confused. thanks.


Solution

  • morganney's comment is correct, but could use some illustration:

    Pass order.staged as a prop on your styled components

    <StyledTableCell align="center" staged={ order.staged }>{order.high}</StyledTableCell>
    

    read it in as another parameter along with theme

    const StyledTableRow = styled(TableRow)(({ theme, ...props }) => ({
      '&:nth-of-type(odd)': {
        backgroundColor: theme.palette.action.hover,
      },
      // hide last border
      '&:last-child td, &:last-child th': {
        border: 0,
      },
    
      // Style according to the value of the passed prop. For example...
      [<selector>]: {
        <CSS_property>: props.staged == "OFFTRACK"
          ? <CSS_property_value_for_offtrack>
          : props.staged == "ONTRACK"
            ? <CSS_property_value_for_ontrack>
            : <CSS_property_value_for_staged> // "STAGED"
      }
      ...
    }));