Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolating variables into a string

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.

like image 793
quanglewangle Avatar asked Nov 04 '16 17:11

quanglewangle


2 Answers

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.

like image 192
TimoStaudinger Avatar answered Oct 12 '22 18:10

TimoStaudinger


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" />
like image 36
user6213384 Avatar answered Oct 12 '22 19:10

user6213384