Nowadays i have this object:
const messages = {
required: field => `${field} needs to be filled!`,
}
That print me:
nome needs to be filled
I'm trying to make a condition in this template string to change the value of the field based in a condition. I tried something like:
const messages = {
required: field => `
${field => {
if(field === 'nome') {
'name'
}
if(field === 'endereco') {
'address'
}
}} needs to be filled!
`,
}
But when i print the message i'm receiving:
field => { if(field === 'nome') { return 'name' } } needs to be filled!
And i need:
name needs to be filled
You make it too complicated
const field = "nome"; const messages = { required: `${field === 'nome'?'name': field} needs to be filled!` } console.log(messages.required) const messages1 = { required: field => `${field === 'nome' ? 'name' : field} needs to be filled!` } console.log(messages1.required("nome"))
I believe that you can only have expressions inside of template literals, not statements (which is what you are trying to do, using an if
is a statement). You can use a ternary to create an expression:
const messages = {
required: field => `${field === 'nome' ? 'name' : field} needs to be filled!`,
};
If you have more than one conditional, then you'll have to break your conditionals out, and flesh out the arrow function a little more:
const messages = {
required: field => {
let display;
if (field === 'nome') {
display = 'name';
} else if (field === 'other condition) {
display = 'other thing';
} else {
display = field;
}
return `${display} needs to be filled`;
},
};
const messages = {
required: field => `${field === "nome" ? "name" : field} needs to be filled!`,
}
Inside the template literals you can't do multiple line expressions, like functions, but you can use ternary operator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.