quite a beginner here but I am struggling to get the following to work. I have an if else condition here that I want the label message to depend on but I am getting an error message Cannot find name 'message' What am I doing wrong? The if else condition is the following:
if(devEnv()) {
const message = useMessageAsString(
<FormattedMessage
id="xxxxxx"
defaultMessage="I've read and accept the <aTerms>Terms of Use</aTerms> and <aPrivacy>Privacy Policy</aPrivacy>"
values={{
aTerms: (msg: string) => (
<a
rel="noreferrer noopener"
target="_blank"
href={URL_TERMS_AND_CONDITIONS_DEV}
>
{msg}
</a>
),
aPrivacy: (msg: string) => (
<a
rel="noreferrer noopener"
target="_blank"
href={URL_PRIVACY_POLICY}
>
{msg}
</a>
),
}}
/>
)
} else {
const message = useMessageAsString(
<FormattedMessage
id="xxxxx"
defaultMessage="I've read and accept the <aTerms>Terms of Use</aTerms> and <aPrivacy>Privacy Policy</aPrivacy>"
values={{
aTerms: (msg: string) => (
<a
rel="noreferrer noopener"
target="_blank"
href={URL_TERMS_AND_CONDITIONS}
>
{msg}
</a>
),
aPrivacy: (msg: string) => (
<a
rel="noreferrer noopener"
target="_blank"
href={URL_PRIVACY_POLICY}
>
{msg}
</a>
),
}}
/>
)
}
And then in the return I want to do this:
<CheckBox
data-testid={'terms_and_privacy_policy'}
checked={formValues.accepted_terms_and_privacy_policy}
onChange={() => {
if (!isValid) {
triggerValidation()
}
onFormFieldChange(
'accepted_terms_and_privacy_policy',
!formValues.accepted_terms_and_privacy_policy
)
}}
label={message}
/>
The problem is that the variable message is only declared within a limited scope. If this code all lives within render() then try defining the message before checking the condition as a mutable var (or let) like this:
var message = "";
if (devEnv()) {
message = useMessageAsString(
...
} else {
message = useMessageAsString(
...
}
return (
...
label={message}
)
Alternatively you can stick with const but use a ternary operator for the assignemnt:
const message = devEnv() ? versionA : versionB;
If, for some reason, you are using class based components, and the message is defined in another function from render then you will need to declare it as a field on the class.