7

Although an experienced programmer I am completely new to js and react.

I am trying to use the react-native-svg component Path within a component of my own. All is clear with the example, but it uses a string literal for the coordinates. E.g.:

<Path d="M 10 20 L 30 40" stroke="red" />

However I want to use coordinates from my component's props x1, y2, x2, y2 instead of literals but I can't figure out how to plant them into the quoted string along with the various characters of which M and L are examples.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
quanglewangle
  • 581
  • 1
  • 5
  • 14

2 Answers2

11

If you are using ES2015 features, template strings would be a possible approach, e.g.:

<Path
    d={`M ${this.props.x1} ${this.props.y1} L ${this.props.x2} ${this.props.y2}`}
    stroke="red"
/>

Note the backticks instead of quotes.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • This works, thanks. Is there any way of viewing the resulting complete Path tag that the code above builds? Something analogous to View Source in for a web page in a browser. – quanglewangle Nov 04 '16 at 21:44
  • You can use template strings like other expressions, they evaluate to a string. I.e.: `const path = \`...\`; console.log(path); return ` – TimoStaudinger Nov 04 '16 at 22:18
2

This look like a similar question that I had. You can pass in an array of items and join them to create your string.

<Path d={['M', x1, y1, 'L', x2, y2].join(' ')} stroke="red" />
Community
  • 1
  • 1
user6213384
  • 135
  • 1
  • 1
  • 9