Using Material-UI with ReactJS: Implementing color alternation in Material-UI <Table/>'s <TableRow/>

I am currently utilizing Material-UI's <Table/> component and I would like to alternate row colors between blue and purple. The first row will be blue, the second row will be purple, and so on for every additional row added.

How can I dynamically switch between two colors for each new row added?

render(){

    return(
        <Table
          multiSelectable={true}
        >
          <TableHeader>
            <TableRow>
              <TableHeaderColumn>First Name</TableHeaderColumn>
              <TableHeaderColumn>Last Name</TableHeaderColumn>
              <TableHeaderColumn>Color</TableHeaderColumn>
            </TableRow>
          </TableHeader>
          <TableBody
            displayRowCheckbox={true}
            stripedRows
          >
              <TableRow style={{backgroundColor: rowIndex%2===0 ? 'blue' : 'purple'}}>
                <TableRowColumn>John</TableRowColumn>
                <TableRowColumn>Smith</TableRowColumn>
                <TableRowColumn>Red</TableRowColumn>
              </TableRow>
              {tableData.map((row,index) => (
                  <TableRow style={{backgroundColor: index%2===0 ? 'blue' : 'purple'}}>
                      <TableRowColumn>{row.firstName}</TableRowColumn>
                      <TableRowColumn>{row.lastName}</TableRowColumn>
                      <TableRowColumn>{row.color}</TableRowColumn>
                  </TableRow>
              ))}
          </TableBody>
        </Table>

Thank you in advance

Answer №1

To implement styled rows in a table, you can create a TableRow and apply the CSS rules for even and odd rows.


Styling Rows with Material UI Version 5 (Styled Components)

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  '&:nth-of-type(odd)': {
    backgroundColor: "white",
  },
  '&:nth-of-type(even)': {
    backgroundColor: "grey",
  },
}));

or

const StyledTableRow = styled(TableRow)`
  &:nth-of-type(odd) {
    background-color: ${({ theme }) => theme.palette.action.hover}; // accessing the theme
  }
  &:nth-of-type(even) {
    background-color: "grey";
  }
`;
(compatible with Typescript and javascript)

Styling Rows with Material UI Version 4 (JSS)

using Typescript:

const StyledTableRow = withStyles((theme: Theme) =>
  createStyles({
    root: {
      '&:nth-of-type(odd)': {
        backgroundColor: "white",
      },
      '&:nth-of-type(even)': {
        backgroundColor: "grey",
      },
    },
  }),
)(TableRow);

using Javascript:

const StyledTableRow = withStyles((theme) => ({
  root: {
    '&:nth-of-type(odd)': {
      backgroundColor: "white",
    },
    '&:nth-of-type(even)': {
      backgroundColor: "grey",
    },
  },
}))(TableRow);

For implementation in your code, here's an example:

render(){
  return(
    <Table multiSelectable={true} >
      <TableHeader>
        <TableRow>
          ...
        </TableRow>
      </TableHeader>
      <TableBody displayRowCheckbox={true} >
        <StyledTableRow>
          ...
        </StyledTableRow>
...
(the stripedRows feature is no longer available in newer MUI versions)

This approach to styling odd/even rows is also outlined in Material-UI's documentation.

Check out these examples to see it in action:

Answer №2

If you're looking for a solution, give this code snippet a try. It has been tested and verified to work smoothly on @version 4.4.2


{
this.state.data.map((row,index)=> (
 <TableRow style ={ index % 2? { background : "#fdffe0" }:{ background : "white" }}> 
...
</TableRow>
))}

Give it a shot and hopefully, it solves your issue. Happy coding! 🚀

Answer №3

Apologies for the delay in response, but I encountered an issue with the stripedRows method not working as expected. As a workaround, I implemented a solution using the modulo operator to alternate between two different colors:

To achieve alternating row colors, you can utilize the modulo operator in your code snippet:

{this.state.data.map((row)=> (
 <TableRow style ={ row.rank % 2? { background : "#fdffe0" }:{ background : "white" }}> 
...
</TableRow>
))}

Implementation based on @Version 4.2.1

Answer №4

If you want to add visual separation between rows in your table, you can utilize the stripedRows prop within the <TableBody> component. However, there may be limitations on customizing colors with this option.

<TableBody stripedRows > </TableBody>

Another approach is to assign a className to the <TableBody> component and apply colors using CSS based on even and odd row rules. In order to ensure these styles take precedence over inline styles, it may be necessary to use !important for those rules.

Answer №5

Searching for a different approach using React Styled Components that is similar to this one

If you are working with Material UI, it's recommended to choose @emotion over styled-components. Although they are similar, the Material UI documentation highlights some limitations when using styled-components. Therefore, opting for @emotion with Material UI can help avoid potential issues in the future.

⚠️ Warning: Using styled-components as an engine currently does not work well in SSR projects. This is because the babel-plugin-styled-components does not correctly detect the usage of the styled() utility within the @mui packages. For more information, refer to this issue. It is highly recommended to use emotion for SSR projects. Material UI

Another reason to consider using @emotion is that Material UI employs it as the default styling engine.

In order to address the issue, I will be utilizing Material UI v5.9.2 and updating several components mentioned previously in this context. The outdated components need to be replaced, and @emotion should be used to incorporate an additional pseudo-class into the TableRow component. Moreover, the color property of td inside the TableRow will be overridden to ensure coherence within a single component.

import Table from "@mui/material/Table";
import TableHead from "@mui/material/TableHead";
import TableBody from "@mui/material/TableBody";
import TableRow from "@mui/material/TableRow";
import TableCell from "@mui/material/TableCell";

import styled from "@emotion/styled";

const TableRowStyled = styled(TableRow)`
  &:nth-of-type(odd) {
    background-color: blue;
  }
  &:nth-of-type(even) {
    background-color: purple;
  }
  & > td {
    color: white;
  }
`;

export default function App() {
  return (
    <div className="App">
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>First Name</TableCell>
            <TableCell>Last Name</TableCell>
            <TableCell>Color</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          <TableRowStyled>
            <TableCell>John</TableCell>
            <TableCell>Smith</TableCell>
            <TableCell>Red</TableCell>
          </TableRowStyled>
          <TableRowStyled>
            <TableCell>Paul</TableCell>
            <TableCell>Row</TableCell>
            <TableCell>Black</TableCell>
          </TableRowStyled>
          <TableRowStyled>
            <TableCell>Doe</TableCell>
            <TableCell>Boe</TableCell>
            <TableCell>Pink</TableCell>
          </TableRowStyled>
        </TableBody>
      </Table>
    </div>
  );
}

https://codesandbox.io/s/reactjs-material-ui-how-to-alternate-colors-between-material-ui-yrm5rl?file=/src/App.tsx

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a Node.js error when trying to insert a row in a

Currently facing an issue with inserting a row into my database table. Below is the structure of the table : mysql> describe emprunt; +------------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | De ...

Setting the default typing language in Protractor: A step-by-step guide

Is there a way to specify a default typing language in my configuration file? While running test cases locally, I am unable to switch keyboard languages during execution as it impacts the typing language for Protractor causing the tests to fail. If you h ...

Using Jquery selectors along with variables to perform targeted search operations

I need assistance creating a JQuery selector that can automatically add an active class to a specific list item based on a variable. The variable sv will hold either 'dom-site' or 'int-site', which correspond to the id of a list item i ...

Is there a way to retrieve object data without using the map JS function?

Currently, I am delving into a project involving React, Redux, and JS. The tutorial I am following incorporates a dummy object within the redux store as illustrated below. const initState = { posts:[ [ {id: '1', title: 'Fi ...

Show the time in hours and minutes (00:00) while rounding off seconds to the nearest minute

I need the time to always display with leading zeros when less than 10. For example, if a task took 3 hours, 7 minutes, and 33 seconds, it should be shown as 03:08. Currently, I have the buttons disabled after they are clicked to prevent restarting the ti ...

Cannot use Axios instance in Next.js due to error stating 'Localstorage is not defined'

I am currently working on a React app and have created an Axios component that I would like to reuse: import axios from 'axios' import dynamic from 'next/dynamic' const baseUrl = 'http://127.0.0.1:8000/' const axiosInstan ...

Having trouble deploying my Express/Next app on Netlify

I am facing issues deploying my Next/Express app on Netlify. While the app functions perfectly locally, I encounter problems when attempting to deploy it using Netlify lambda function. Here are the links to my test git repositories: https://github.com/La ...

Preventing default form submission in jQuery: How to cancel it when a certain condition is met

I have a contact form where I validate the input values upon clicking on the submit button. If there is at least one empty input, I trigger an alert and prevent the form submission by using preventDefault. However, if all inputs are filled and submitted, t ...

Creating an insert query in Node.js with frontend HTML and connecting it to a PostgreSQL database is a crucial task in web

I am new to working with Node.js, PostgreSQL. Currently, I am tackling the login form code and facing several issues related to the POST method. I am using HTML, Node.js, and PostgreSQL for this project. Please assist me with solving these problems by revi ...

Tips on displaying five bootstrap modal popups simultaneously on a webpage

I'm looking to achieve a specific functionality that involves opening multiple bootstrap modal popups on one page simultaneously without overlapping each other. Specifically, I need a button to trigger the opening of five separate modals each containi ...

When nodemon is executed, it encounters an "Error: Cannot find module" issue, indicating that it may be searching in the incorrect directory

I recently encountered an issue with my Node.js project that utilizes nodemon. Despite having the package installed (located in /node_modules), I am experiencing an error when trying to start my Express server with nodemon through a script in my package.js ...

Avoid the need for props when implementing a component with a higher order component

Running into an issue with HOC and typescript. The compiler is asking for a value that is received from the HOC. Here's the component using the HOC: function Coupon(props: WithAlertProps): JSX.Element { return <p>test {props.error}</p> } ...

Navigating up and down in a horizontal row of 'tabs'

For a school project, I am in the process of creating a website that I wanted to make unique and different. However, I have encountered a major challenge with a tight deadline approaching. Any assistance would be greatly appreciated. Let's address ...

Convert a portion of an object into a string to send in a server request

I have customized the fetch method of a Backbone Collection to make a request to a different URL under certain conditions, and I need to include some data with it. The modified fetch method (which I obtained from another solution on Stack Overflow) is as f ...

Is there a different method I can utilize to create a conditional statement for assigning a value in JavaScript?

I have this code snippet that seems a bit unclear to me: if (!app.config.admin.examStatusId) { app.config.admin.examStatusId = exam.examStatus.dataPlus[0].id; } Do you have any suggestions on how I could rewrite this more clearly without using an if s ...

Exporting SVG to image in Ionic is successful on Android devices, but the image gets cut off when viewed on

I am facing an issue with exporting an SVG as a base64 encoded image and sending it to the server for storage on Google Cloud Storage. The process works fine on Android and in browsers, but fails when attempted on a physical device running IOS. On IOS, t ...

Ways to update the state of an array without clearing the existing array items

I am attempting to add fetched array items to an existing state that already contains items (with plans to include pagination). However, when I try using code similar to setMovies((prevMovies) => [...prevMovies, ...arr1]), I encounter a Typescript erro ...

Unable to alter the content within an iframe when using the Google Chrome browser

Currently, I am tackling a project that involves incorporating animations into multiple generated pages. These pages are nested within iframes on the main index page. As part of this same project, I need to dynamically add elements to these iframe-embedd ...

Waiting for the UI data filter to be available in Selenium

Within an application, numerous fields are present with individual filters (text boxes). As soon as a user enters a value in any of the filters, the UI data (in a table) immediately refreshes. I prefer to wait for the UI data to load before applying anoth ...

Centering elements in CSS with a full-width approach

My goal is to centralize all the elements on a webpage so that when the browser size is modified, the content shifts accordingly. Currently, I am using the following CSS code: margin: 0px auto; width: 670px; However, I am facing a challenge in trying to ...