Search code examples
reactjsreact-nativereact-componentreact-styleguidistreact-button

how to pass svg as a prop to a pressable component


I'm using lot of svg images with the help of these two libraries

"react-native-svg": "^12.1.0",
"react-native-svg-transformer": "^0.14.3",

Then I can able to import and use svg images like below.

import Logo from '../assets/svg/img.svg';
...
...
<Logo height={60} />
...

The below is my custom button

***imaginary part // import Logo from '../assets/svg/img.svg';

const ButtonPressable = (props) => {
  return (
    <View>
      <Pressable
        style={[
          props.backgroundColor
            ? {backgroundColor: props.backgroundColor}
            : {backgroundColor: '#0077b6'},
        ]}>
        <Text>
          {props.text ? props.text : ''}
        </Text>

***imaginary part // <Logo height={60} />

      </Pressable>
    </View>
  );
};

I'm using above component like below

<ButtonPressable text="Login" backgroundColor="red" />

If you look at the imaginary part in above code. With that way, I can show svg images inside a component. But, I need to display svg images as a prop like below.

<ButtonPressable text="Login" backgroundColor="red" svg="../assets/svg/img.svg" />

How to pass svg path as a prop and display inside a component ?


Solution

  • Here is an example of how to pass SVG imported from the main component. The idea is ButtonPressable will have a prop, svg, it could be anything but it can be SVG as well. Please modify ButtonPressable as below

    const ButtonPressable = (props) => {
      return (
        <View>
          <Pressable
            style={[
              props.backgroundColor
                ? {backgroundColor: props.backgroundColor}
                : {backgroundColor: '#0077b6'},
            ]}>
            <Text>
              {props.text ? props.text : ''}
            </Text>
    
    {props.svg? <props.svg height={60} /> : null}
    
          </Pressable>
        </View>
      );
    };
    

    and then import them anywhere like this and pass SVG

    import Logo from '../assets/svg/img.svg';
    <ButtonPressable text="Login" backgroundColor="red" svg={Logo} />
    

    This will keep ButtonPressable reusable.