1

How do I pass {currentyear} to label component?

let text = "<p><span>Year {currentyear}</span></p>";
<Label text={dangerouslySetInnerHTML={{__html: text}}}

Label is a component that takes in text as property and displays it on the document

2
  • 1
    Obligatory: Do you need to use dangerouslySetInnerHTML here? If that is actual code and not just an example, it seems like you could just nest the labels content normally. Commented Nov 16, 2021 at 13:53
  • You said you are getting this string from the JSON response, but how do you expect to get your JS variable inside this JSON response? Commented Nov 16, 2021 at 13:57

1 Answer 1

2

This is just a literal string:

"<p><span>Year {currentyear}</span></p>"

It sounds like you're looking for a template literal:

`<p><span>Year ${currentyear}</span></p>`

This will evaluate the currentyear variable into the resulting string when first setting the text variable.


Edit: In a comment below you indicate that this string value comes from an external source:

"<p><span>Year {currentyear}</span></p>"

Which means it's a string and can't be a template literal. In that case you can simply perform your string replacement manually. For example:

let text = yourString.replace('{currentyear}', currentyear);

The point of all of this is that it's not really a question of "using a variable in dangerouslySetInnerHTML". You're already doing that (using the text variable). What you're trying to do is simply manipulate a string in JavaScript. There is a lot of string functionality you can use.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting that string from a JSON response.
@UthkarshCheekati: Can you clarify that in the question? If there's information about the problem that you share piece-by-piece in response to answers then that's called a "moving target" and it makes answering very difficult.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.