Customize the appearance of the "Collapse" component in the antd react library by overriding the default styles

Incorporating JSX syntax with *.css for my react component. Displayed below is the jsx code for the antd collapse section.

    <Collapse
      defaultActiveKey={["1"]}
      expandIconPosition="right"
    >
      <Panel
        header="This is panel header with arrow icon"
        key="1"
      >
        <div>
          Body-123
        </div>
      </Panel>

    </Collapse>

Presently, I want to specifically style (border: "3px solid red") the header section of the Collapse using the following css:

.ant-collapse > .ant-collapse-item > .ant-collapse-header

However, the challenge lies in the fact that I am looking to achieve this dynamically based on a condition within the jsx code. Each panel should have a different border color depending on certain data.

Thanks in advance.

Answer №1

I encountered a similar situation where I needed to selectively style the header background color in each Panel component without affecting the content. To solve this, I decided to utilize a CSS variable to define the background color rule in my stylesheet.

To achieve this, you can set a CSS variable with the value calculated in JavaScript using the style object:

style={{ ["--header-border"]: category.border }}

In your CSS file, you can then reference this variable as a rule in your selector:

.collapse-panel-custom > .ant-collapse-header {
  border: var(--header-border, 1px solid black);
}

Check out this CodePen example showcasing how this approach is implemented for styling the panel header border:

https://codepen.io/faltherr/pen/ZEBzeJe

Answer №2

Utilize the className attribute to dynamically assign classes based on specific conditions, then use the class name to apply styling such as borders.

Below is an illustration demonstrating how to toggle borders upon button click:

Component

const App = () => {
  const [hasBorder, setBorder] = React.useState(false);
  return (
    <React.Fragment>
      <Button onClick={() => setBorder(!hasBorder)}>Set Border</Button>
      <Collapse
        className={hasBorder ? "" : "active"}
        defaultActiveKey={["1"]}
        expandIconPosition="right"
      >
        <Panel header="This is panel header with arrow icon" key="1">
          <div>Body-123</div>
        </Panel>
      </Collapse>
    </React.Fragment>
  );
};

Style

.active.ant-collapse > .ant-collapse-item > .ant-collapse-header {
  border-top: 3px solid black;
}

View the demonstration here: https://codesandbox.io/s/suspicious-grothendieck-submf

Trust this explanation proves beneficial!

Answer №3

If you want to conditionally set inline styles, take a look at the code snippet below:

const hasBorder = true;
<React.Fragment>
  <Collapse
    style={hasBorder ? {border: '3px solid black'} : {}}
    defaultActiveKey={["1"]}
    expandIconPosition="right"
  >
    <Panel header="This is panel header with arrow icon" key="1">
      <div>Body-123</div>
    </Panel>
  </Collapse>
</React.Fragment>

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

The controller remains unresponsive when attempting to activate the button on the webpage

I'm a beginner in frontend development and I'm currently working on a website that uses Thymeleaf. On this website, there is a div block with a button. Please take a look at the HTML code below, specifically the button at the last three rows. &l ...

The transparency of my navbar renders it elegant, yet I desire to imbue the toggle background with a vibrant hue

I'm facing an issue with the transparent Navbar I built in Bootstrap 5. On mobile toggle view, the navigation links are getting lost within the text of the hero image. To resolve this, I want to keep the main navigation bar transparent and change the ...

Unexpected behavior with jQuery AJAX Callback function:

When attempting to extract data from the success part of an AJAX call, I implemented a callback function for this purpose. Here is the code snippet: var data2; $(function () { function callback(data) { console.log(data); data2 = JSON.parse(data ...

Issue with Bootstrap contact form functionality in PHP not working

I have experience in coding HTML and PHP, but unfortunately, [email protected] (mail address) is still unable to receive emails from my website (http://cloudsblack.info/) and when I click the submit button, it leads to a blank page (http://cloudsblack.info ...

Integrating Node.js into a Grails application

Apologies if I sound inexperienced. I primarily work on front-end development. Currently, I am tasked with designing new mobile views for a Grails app. My plan is to utilize Reactjs for the front-end development, but I am unsure about incorporating Nodejs ...

How can you pass two distinct variables in a JavaScript function?

This is the JavaScript code for my first page: <script> function MessageDetailsById(id) { $("#active"+id).css({"color":"red"}); var http = new XMLHttpRequest(); var url = "Ajax.php"; ...

Employing the identical directive within a directive [angularjs]

My requirement is to utilize the same directive within another directive, based on a conditional parameter. However, every time I attempt to do this, it appears to enter an infinite loop. It seems like the templates are being preloaded and causing a recurs ...

How can two unique links toggle the visibility of divs with two specific IDs?

I am developing an interactive questionnaire that functions like a 'create your own adventure' story. The questions are shown or hidden depending on the user's responses. Below is the HTML code: <!-- TIER 3 ============================== ...

AngularJS NG-Grid displaying incorrect value for select cell

I'm working on creating a table with a column that needs to be selected based on a value received from the server. The server sends me 4 as the value, but the first option is always selected instead. $scope.lotteryOptions = { data: 'myDa ...

Are there any "Undefined" tabs hiding in your RMarkdown tabsets?

After knitting my RMarkdown document to an HTML file, I noticed that the tabs appeared as shown below: https://i.sstatic.net/x1p70.png However, when I save and share the document with my audience, I encounter an issue where these tabs are labeled as "und ...

Freshening up the data source in a Bootstrap Typeahead using JavaScript

I'm trying to create a dropdown menu that displays options from an array stored in a file called companyinfo.js, which I retrieve using ajax. The dropDownList() function is called when the page loads. function dropDownList (evt) { console.log("dr ...

Building personalized error messages using graphql-js and express

It has come to my attention that you have the ability to create customized errors within graphql and graphql-express. https://codeburst.io/custom-errors-and-error-reporting-in-graphql-bbd398272aeb I recently implemented a custom Error feature, but it see ...

Is it possible to include more than one ng-app directive on a single HTML page in AngularJS?

When working with Angular JS, I've noticed that I only get the desired output if I remove either the ng-app directive for demo1 or the models. It seems like having two ng-app directives active at the same time causes issues. As a beginner in Angular J ...

When evaluating code with eval, properties of undefined cannot be set, but the process works seamlessly without

Currently, I am attempting to utilize the eval() function to dynamically update a variable that must be accessed by path in the format myArray[0][0[1][0].... Strangely enough, when I try this approach, I encounter the following error: Uncaught TypeError: ...

Validating textfields and dropdowns for dynamic HTML identifiers using jQuery

I am attempting to validate a dropdown and text field together. Both fields can either be left empty or both must be filled. The HTML ids are generated dynamically. I have tried the code below but it is not working as expected. Here are the resources I use ...

Is there a way to retrieve the count of each item within an array by utilizing the .map method in the React library

Currently, I am attempting to retrieve the quantity of each object in an array and then incorporate it into my JSX code to indicate which one it is. The data is being extracted from a file named tableData.js export const data = [ {price: 1500, isSold: f ...

Effortlessly adjust item width in CSS Grid

I am currently utilizing CSS Grid to showcase various tags. If a tag happens to be quite large, with a width exceeding 150px, I would ideally like that specific item to expand across multiple columns as necessary. For instance, in the visual representation ...

The object in three.js disappears from the scene but remains visible

I am attempting to showcase text as a sprite in three.js and aim to move the sprite along with an object. I achieve this by utilizing a canvas to generate a texture, which is then mapped using SpriteMaterial to create a sprite from it. However, when I remo ...

What is the process for transforming an asynchronous method into a synchronous version?

I am currently working on creating a functionality similar to the core fs module's methods, where there is an Async method by default and a Sync method if requested like fs.readDir() and fs.readDirSync(). In my case, I have a method named fetchUrls w ...

Processing ajax requests in Rails 4 using HTML format

I'm currently in the process of setting up ajax functionality for my contact form and I am currently testing to ensure that the ajax call is being made. When checking my console, I noticed that it is still being processed as HTML and I cannot seem to ...