Add Active Class When Specific Variables Equal on React

In React, you can conditionally add an “active” class to an element based on certain variables using conditional rendering. In your code snippet, it appears that you want to add the “active” class to a list-group-item element when the invoiceId is equal to invoice.number. Here’s how you can achieve this in React:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import React from 'react';

function YourComponent({ invoiceId, invoice }) {
  return (
    <div>
      {/* ... Other JSX code ... */}
      <div className={`list-group-item list-group-item-action ${invoiceId === invoice.number ? 'active' : ''}`}>
        {/* Your content for the list item */}
      </div>
      {/* ... Other JSX code ... */}
    </div>
  );
}

export default YourComponent;

In the code above:

  1. We assume you have a component called YourComponent that takes invoiceId and invoice as props.

  2. Inside the return statement, we use a template literal to create the className dynamically for the list-group-item element. We use a conditional (ternary) operator to check if invoiceId is equal to invoice.number. If they are equal, the ‘active’ class is added; otherwise, an empty string is added.

  3. This approach ensures that the “active” class is only added to the list-group-item when the condition invoiceId === invoice.number is met. If the condition is not met, no additional classes will be added.

Make sure to replace YourComponent with the actual name of your component and ensure that invoiceId and invoice.number are correctly passed as props to your component.

0%