Home > Back-end >  Import SVG in parent and pass to child
Import SVG in parent and pass to child

Time:01-11

Currently I import Icons like this

//index.ts file for svgs
import BackArrow from './back-arrow.svg'

export {
  BackArrow,
  ...
}

In a component i can now import and use it easily

import { BackArrow } from '../../assets/images'
....

return <BackArrow />

Now I tried to make a (child) component which should display two buttons and a text, which are passed by the parent component.

Parent uses the child like this:

      <Button
        label='hi'
        iconLeft={BackIcon}
        buttonTheme={BUTTONS_THEME.dark}
      />

Child looks like:

//Styled components (ThemedButton, Icon, Label)

const Button = ({  label,  iconLeft,  iconRight,  theme}) => {
  <ThemedButton>
     {iconLeft && <Icon theme={theme} xml={iconLeft} />}
     <Label theme={theme}>{label}</Label>
     {iconRight && <Icon theme={theme} xml={iconRight} />}
  </ThemedButton>

and this all works fine, if in the parent component I import the svg like this: import BackArrow from '../../assets/images/back-arrow.svg' but i want to use the "normal" way to import it as I do everywhere else in the App, like this: import { BackArrow } from '../../assets/images'

Anyone any idea how to solve this? I tried to pass the Icons like this <Button leftIcon={<BackArrow />}... />, but I can't get this working, as I don't know how I can use and style the icon in the child.

CodePudding user response:

I don't know what you are using for your build processes. but it's probably because of loaders that you use for loading svg. If you import your svg like this: import BackArrow from '../../assets/images/back-arrow.svg' it's probably load it as dataURL. And if you import your svg like this: import { BackArrow } from '../../assets/images' it imports as react component. Thus you can not use this as xml props of a Icon.

CodePudding user response:

I think what you are trying to do is use your BackArrow in your child as <BackArrow />

The below approach is for a CRA app where you can import svg as a ReactComponent

I solved a similar issue by following this approach.

import is as import { BackArrow } from './back-arrow.svg

Continue to pass it to child as

 <Button
    label='hi'
    iconLeft={BackIcon}
    buttonTheme={BUTTONS_THEME.dark}
 />

but, now in child access it as so,

const Button = (props) => {
  <ThemedButton>
     {props.iconLeft && <props.iconLeft ... />}
     <Label theme={props.theme}>{props.label}</Label>
     {props.iconRight && <props.iconRight ... />}
  </ThemedButton>

EDIT:

In the child component when you have <props.iconLeft ... /> then this is equivalent to <BackArrow /> so now you are free to style it, essentially treat it the way you would in the parent when you had <BackArrow />. Destructuring your props in the child doesn't quite work here.

  •  Tags:  
  • Related