Reputation: 617
I am using JSX syntax with *.css for my react component. Below is the antd collapse jsx code.
<Collapse
defaultActiveKey={["1"]}
expandIconPosition="right"
>
<Panel
header="This is panel header with arrow icon"
key="1"
>
<div>
Body-123
</div>
</Panel>
</Collapse>
Now, I would like to only style(border: "3px solid red"
) the header part of the Collapse, which I could do using below css
.ant-collapse > .ant-collapse-item > .ant-collapse-header
But the issue is, I would like to do it dynamically depending on some condition in the jsx code. That is I have a few of such panels and each should have different border color depending on some data.
TIA
Upvotes: 1
Views: 13591
Reputation: 66
I ran into a similar issue where I wanted to conditionally style the background color of the header in each Panel component but not the content. I elected to use a css variable to provide a rule for the background color in my style sheet.
You can add a css variable with the value you derive in JavaScript through the style object:
style={{ ["--header-border"]: category.border }}
In your css file you can then consume this value in as a rule in your selector:
.collapse-panel-custom > .ant-collapse-header {
border: var(--header-border, 1px solid black);
}
Here is a codepen of this method applied to the border of the panel header:
https://codepen.io/faltherr/pen/ZEBzeJe
Upvotes: 4
Reputation: 9642
You can set inline style conditionally, check code 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>
Upvotes: 1
Reputation: 2774
You can use className
to dynamically set the class based on your condition and use the class name to set the border.
Here is an example which toggles border based on 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;
}
Check the demo here: https://codesandbox.io/s/suspicious-grothendieck-submf
Hope this helps!
Upvotes: 1