question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to increase svg width based on text

See original GitHub issue

I’m using this component in my app in many places. recently i found some difficulty with the usage. if i have long text the width of the svg must be adjustable based on the text and the text must be in the center of the box. For suppose microsoftteams-image 3

My code is something like below

<View style={{marginTop: 50,width:'100%', height: 50, justifyContent: 'center', alignItems: 'center', flexDirection:'row'}}> <Svg width={200} height={50} style={{backgroundColor:'yellow'}}> <SvgLinearGradient id="Gradient" x1="0%" x2="100%" y1="0%" y2="0%"> <Stop stopColor="#C2515D" offset="0%"/> <Stop stopColor="#853C5E" offset="100%"/> </SvgLinearGradient> <Text fill="url(#Gradient)" x="50" y="20" fontSize="18" fontWeight="700" textAnchor="start" > hi hello hi hih hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi i hi </Text> </Svg> </View>

here based on the text the width of the svg must be increased how?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:19

github_iconTop GitHub Comments

1reaction
msandcommented, Jan 22, 2019

Slightly more involved version:

import * as React from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import { LinearGradient, Stop, Text, Rect, Svg } from 'react-native-svg';

export default class App extends React.Component {
  state = {};
  onTextLayout = e => {
    const textLayout = e.nativeEvent.layout;
    const { height, width, x } = textLayout;
    const { rootWidth, textWidth, textX } = this.state;
    const hasMeasured = rootWidth && textWidth;
    //console.log('text', textLayout);
    if (height && !textWidth) {
      this.setState({ textWidth: width });
    }
    const { width: w, height: h } = Dimensions.get('window');
    const portraitMode = w < h;
    if (hasMeasured && portraitMode && !textX) {
      this.setState({ textX: x });
    }
  };
  onRootLayout = e => {
    const rootLayout = e.nativeEvent.layout;
    const { height, width } = rootLayout;
    //console.log('root', rootLayout);
    this.setState({ rootWidth: width, rootHeight: height });
  };
  render() {
    const { rootWidth, rootHeight, textWidth, textX = 0 } = this.state;
    const { width: w, height: h } = Dimensions.get('window');

    const portraitMode = w < h;
    const hasMeasured = rootWidth && textWidth;
    const ready = hasMeasured && (!portraitMode || textX);
    const measuredRatio = (textWidth + (portraitMode ? textX : 0)) / rootHeight;
    const width = 100 * measuredRatio;

    const viewBox = hasMeasured ? `0 0 ${width} 20` : '0 0 100 100';
    //console.log('viewBox', viewBox, rootWidth, portraitMode);

    return (
      <View style={styles.container}>
        <Svg
          width="100%"
          height="100"
          viewBox={viewBox}
          onLayout={this.onRootLayout}
          style={{ backgroundColor: 'yellow' }}
        >
          <Rect
            x="0"
            y="19"
            height="1"
            fill="url(#Gradient)"
            width={ready ? width : '100%'}
          />
          <LinearGradient id="Gradient" x1="0%" x2="100%" y1="0%" y2="0%">
            <Stop stopColor="green" offset="0%" />
            <Stop stopColor="blue" offset="100%" />
          </LinearGradient>
          <Text
            y="18"
            fontSize="18"
            fontWeight="700"
            onLayout={this.onTextLayout}
            fill={ready ? 'url(#Gradient)' : 'none'}
          >
            Kushi kapoor
          </Text>
        </Svg>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

0reactions
albertcitocommented, May 19, 2020

I tried to write this example with hooks and TS. But I’m getting this error in the tag <Text> and <Svg>

Unknown event handler property onLayout

I need to change the font size to adjust it to the size of the container.

Read more comments on GitHub >

github_iconTop Results From Across the Web

textLength - SVG: Scalable Vector Graphics - MDN Web Docs
The textLength attribute, available on SVG <text> and <tspan> elements, lets you specify the width of the space into which the text will ......
Read more >
Automatically scale SVG to fit width of child contents (e.g. text ...
I would like the <svg> to grow to match the width of the text element, like if a normal DOM element is set...
Read more >
How to increase svg width based on text · Issue #907 - GitHub
I'm using this component in my app in many places. recently i found some difficulty with the usage. if i have long text...
Read more >
Responsive SVGs with Constant Font Size - Florian Eckerstorfer
In this post I present an overview of some techniques to keep the size of text constant in responsive SVGs.
Read more >
How to Scale SVG | CSS-Tricks
A first glance at the SVG specifications would suggest that the height and width attributes on the top-level svg element will implicitly set...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found