What is the best way to dynamically render classes based on conditions in a table using React Bootstrap?

I am looking for a way to dynamically change the color of a class based on the transaction data in a table.

import React from "react";
import Table from "react-bootstrap/Table";
import "./TableComponent.css";

const TableComponent = ({
  Movement
}) => {
  const colorType = Movement.map((obj) => {
    let colorClass = "p-1 ";
    if (obj.Type === "Deposit") {
      colorClass += "depo";
    } else {
      colorClass += "wit";
    }
    return colorClass;
  });

  const renderMovements = (Movement, i) => {
    return (
      <tr key={i}>
        <td className="p-3">
          <div className={colorType}>{Movement.Type}</div>
        </td>
        <td className="p-3 App" colSpan="2">{Movement.Date}</td>
        <td className="p-3 App">{Movement.Amount}</td>
      </tr>
    );
  };

  return (
    <div>
      <Table striped bordered hover size="sm">
        <thead>
          <tr>
            <th className="p-2 App">Transaction</th>
            <th className="p-2 App" colSpan="2">Date</th>
            <th className="p-2 App">Amount</th>
          </tr>
        </thead>
        <tbody>{Movement.map(renderMovements)}</tbody>
      </Table>
      <button onClick={testColor}>Test Color</button>
    </div>
  );
};

export default TableComponent;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

The issue with this code is that the last class added is applied to every element. I want to differentiate between withdrawals and deposits by displaying red background for withdrawals and green for deposits.

Answer №1

Your function colorType should return a string, but it is currently returning an array.

  const colorType = (movement) => {
    let colorClass = "p-1 ";
    if (movement.Type === "Deposit") {
      colorClass += "depo";
    } else {
      colorClass += "wit";
    }
    return colorClass;
  });

When rendering, use the following code:

<div className={colorType(Movement)}> 
 {Movement.Type}
</div>

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

Pattern for identifying JavaScript import declarations

My task involves using node to read the contents of a file. Specifically, I am looking to identify and extract a particular import statement within the file that includes the "foo-bar" package. The goal is to match only the line or lines that contain the ...

The pdf generation feature of pdf-creator-node in Linux seems to be malfunctioning

An error occurred with code EPIPE at afterWriteDispatched (internal/stream_base_commons.js:154:25) at writeGeneric (internal/stream_base_commons.js:145:3) at Socket._writeGeneric (net.js:784:11) at Socket._write (net.js:796:8) ...

What is the best way to forward a brief URL link to a website address?

I currently have two domains in my possession: myVeryLongSiteDomain.com mVeryShortURL.co I am looking to create the following short URLs: mVeryShortURL.com/123456789 mVeryShortURL.com/a-DSa131_ These short URLs need to redirect to the long site domai ...

Splitting React code into two bundles - one for newer browsers and one for older browsers for efficient loading

While working on a new React.js project with create-react-app, I am exploring the idea of component-based code splitting. Is it feasible to serve two different bundles based on the browser version? For example, can I provide a version with necessary transf ...

JavaScript code using the Jquery library to retrieve the following article from 'cached memory'

I am aware of the easier CSS options for my question, but I am determined to learn JS (Jquery), so please bear with me. My plan: Menu-items are connected to articles within my content division. Initially, only the first article (#intro) is displayed. All ...

What is the rationale behind TypeScript's decision to permit omission of "this" in a method?

The TypeScript code below compiles without errors: class Something { name: string; constructor() { name = "test"; } } Although this code compiles successfully, it mistakenly assumes that the `name` variable exists. However, when co ...

What is the relationship between three.js transforms and CSS3 3D-transforms?

I am developing a unique open-source tool for exploring and visualizing the complexities of human anatomy. At the center of this tool is a dynamic 'chessboard' that occupies the majority of the screen. As you drag the board, various CSS3 3D-tran ...

Checking the efficiency of Graphql API

Currently, I am in the process of optimizing key features within my Node.js API which incorporates GraphQL. This API serves as a proxy, receiving requests from various sources and forwarding them to multiple APIs based on the request. I am interested in ...

Click to shift the div downwards

Currently, I have a piece of javascript applied to a div that directs the user to a specific link: <div style="cursor:pointer;" onclick="location.href='http://www.test.com';"> I am wondering if there is a way to add an effect where, upon ...

What could be causing this issue with my Mongoose.js program when it freezes during a 'nested' save operation?

[edit]: I made a revision to the previous question, providing a very precise reproducible example. This is the program I've created. I have developed two Schemas named ASchema and BSchema with collections A and B respectively. Then, I generated ...

What could be causing my React Signals dialog to not open in this scenario?

I have been attempting to manage a MUI dialog using a signal, however, even with the < p > tag, the value from the signal is not being displayed. Surprisingly, the value of the signal does change in the console. Oddly enough, clicking the FAB button ...

Utilize CSS to break through a backdrop

I have come across a rather peculiar question, and I'd like to elaborate with a code snippet: .container { width: 200px; height: 200px; background: rgba(200, 200, 200, .87); } .pin { position: absolute; left: 50px; top: 20px; } .overl ...

Using AngularJS ng-repeat with jQuery find yields a single element result

I'm in the process of developing my very first AngularJS application, and I've run into an issue with the jQuery find function. Essentially, what I'm attempting to do is utilize a custom HTML component that contains a list of buttons generat ...

Nested Classes in JQuery

Looking for help with fading in text using jQuery. Despite setting everything up, it doesn't seem to be working. Can someone assist me with this issue? Here is my current code: .nav ul li { opacity: 0; padding: 0px 50px; transition: opacity 2s ease-i ...

Creating a dropdown menu in Bootstrap 5 without using any of the Bootstrap

In my Angular application, I have a header with icons and pictures that I would like to use as dropdown menus. The code snippet for this functionality is shown below: <li class="nav-item dropdown"> <a class="nav-li ...

Ways to delete a header from the req object in Express

Can anyone help me understand how to remove a header from the req object in Express? I've heard that using res.disable("Header Name") can do this for the res object, but it doesn't seem to work for req.headers. ...

Adding complex JSON format to an HTML table involves formatting the data correctly and then using

Utilizing AJAX, I fetched a JSON response and am now looking to map the JSON data into an HTML table structured like this: { "records": [{ "type_id": 000001, "type_desc": "AAAAAA", "type_createby": "Adam" }, { "type ...

What is the process for playing an audio file on a mobile device?

Recently, I encountered an issue with a jQuery statement that plays a created audio file. Strangely, the file plays correctly on my computer but not on my mobile phone. Despite max volume settings, there is no sound when trying to play it on the mobile dev ...

Sharing tips for sending error objects to a socket.io callback

Utilizing callbacks with socket.io Client side code : socket.emit('someEvent', {data:1}, function(err, result) { console.log(err.message); }); Server side code : socket.on('someEvent', function(data, callback) { callback(ne ...

The XMLHTTP request and Chrome developer tools do not show matching information

I am currently downloading a file in chunks using XMLHttpRequest and the Range header. Everything is going smoothly, except for when I try to determine if I have downloaded the last chunk. Here's a snapshot of the initial request and response for the ...