coder82
coder82

Reputation: 156

With antd custom svg icons, how to pass props down to svg?

The example at the end of this page is not clear: antd custom icon instructions, how do I pass the "fill" property to the component when using a custom svg:

<Icon component={MessageSvg} />

This doesn't work:

<Icon component={MessageSvg} fill="red"/>

as it doesn't paint the Icon red, but standard gray. Isn't antd supposed to pass down the props?

but but, If I do this:

<MessageSvg fill="red" />

then it works. So in theory I could wrap Icon and do an HOC to solve this, but I am sure I am missing something maybe.

I am using the webpack extension @svgr/webpack

 {
            test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
            use: [
                {
                    loader: 'babel-loader',
                },
                {
                    loader: '@svgr/webpack',
                    options: {
                        icon: true,
                    },
                },
            ]
        }

Upvotes: 6

Views: 7825

Answers (3)

Artyom Vancyan
Artyom Vancyan

Reputation: 5380

Following component allows to change icon attributes with css

import SVG from "react-inlinesvg";
import MessageSvg from "./Message.svg";

export const MessageIcon = (props) => (
    <Icon component={(iProps) => <SVG src={MessageSvg} {...iProps}/>} {...props}/>
)

Example of the usage

export const App = () => (
    <MessageIcon className="icon-primary"/>
)

Then we can change all properties we need

.icon-primary {
   color: #32E0C4 !important;
   font-size: 1rem !important;
}

P.S. This method works well with svg files downloaded from iconfont.cn

Upvotes: 1

coder82
coder82

Reputation: 156

Finally I found out.

<Icon component={() => <MessageSvg fill="green"/>}/>

Upvotes: 6

Shivam Gupta
Shivam Gupta

Reputation: 1238

Yeah, as per the custom-icon demo you'll have to pass the fill style as props like you did

<MessageSvg fill="red">

change it to

<Icon component={MessageSvg} style={{color: "red", fill: "red"}}>

Also notice how they use the fill="currentColor" in the actual svg component. Hope it helps!

Upvotes: 0

Related Questions