Home > Mobile >  Spread props for a react component
Spread props for a react component

Time:01-19

I have all my SVCs as react components as seen below, and I want the option to pass the color attribute as a prop to override the components default color. However, adding a props attribute does the job, it leaves me with an ugly object that I have to define in the parent component. How do I fix this?

SVG

import React, { SVGAttributes } from 'react'

interface WalletProps {
  props?: SVGAttributes<any>
}

const Wallet: React.FC<WalletProps> = ({ ...props }) => {
  return (
    <svg
      aria-hidden="true"
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 512 512"
      {...props}
    >
      ...
    </svg>
  )
}

export default Wallet

So to add a color, I've ended up with this: <Wallet props={{ color: 'red' }} /> but I want <Wallet color="red" />. I ideally want this to work with height, width, className, and all other attributes that the SVG element uses.

Many thanks

CodePudding user response:

You can declare WalletProps as React.SVGProps<SVGSVGElement>, so that it will contain all the attributes of an SVG element. There is then no longer any need to destructure props:

type WalletProps = React.SVGProps<SVGSVGElement>;

const Wallet: React.FC<WalletProps> = (props) => {
  return (
    <svg
      aria-hidden="true"
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 512 512"
      {...props}
    >
      ...
    </svg>
  )
}

In the event that you have other props to merge into it, e.g. foo and bar, then it is a matter of creating a union type:

type WalletProps = React.SVGProps<SVGSVGElement> & { foo: FooType, bar: BarType };
  •  Tags:  
  • Related