Home > Enterprise >  React: Passing a template literal as a prop
React: Passing a template literal as a prop

Time:06-25

I have a component that has a border: string prop (typescript). The way I want to pass in this prop is like below:

<Button border={`'1px solid' ${borderColor}`} />

Where ${borderColor} is a state variable. My prop is working when hard-coding the border, like this:

<Button border="1px solid black" />

But how can I make it work when mixing a string/state variable?

Thanks

CodePudding user response:

In this code sample, you can remove the quotes around 1px solid and it should work for you. With template strings, the tick marks (`) are the only string wrappers you need!

Here is a demo showing you how it works: https://codesandbox.io/s/magical-glitter-sbjrqf?file=/src/App.js

CodePudding user response:

Try:

<Button border={`1px solid ${borderColor}`} />

You can read more about template literals here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

  • Related