I want to use map in my Jsx in react and it has error because I use it with ternary expressions. Can anyone help me?
{tf > 0 ? {products.map(product => <CartProduct key={product.id} productData={product}/>)} : ''}
CodePudding user response:
You have error in your syntax. You should not use curly braces if you are returning directly. Curly {}
braces are only used when you have some processing/calculations to do and then don't want to return anything or if return something and not the complete function which you wrote. For example, use curly braces here:
const temp = () => {
let a=20;
console.log('a',a);
};
Notice that I don't want to return anything in the function.
However, if you don't have anything to process or want to directly return what you are processing, use round ()
brackets.
const temp = () => {
let a = 20;
console.log('a', a);
return (
<div>
<h1>Hi</h1> there
</div>
);
};
Notice that I am returning multiple lines above.
Also, if you have multiple lines of code to return, then use round ()
brackets, otherwise just return the value.
const temp = () => {
let a = 20;
console.log('a', a);
return 'Hi';
};
In this ternary operator, you are returning products.map(...
function and for each product, you are returning <CartProduct
component. This is a single statement (since map is a function), so you don't need to use round ()
also. So, the correct way to write the code is:
{tf > 0 ? products.map((product) => <CartProduct key={product.id} productData={product} />) : ''}
However, if you want to use round ()
brackets for single-lined return statements, you can do that too.
const temp = () => {
let a = 20;
console.log('a', a);
return ('Hi');
};
So, you can also rewrite your code as:
{tf > 0 ? (products.map((product) => <CartProduct key={product.id} productData={product} />)) : ''}
Both the ways are correct.
CodePudding user response:
{tf > 0 ? products.map(product => <CartProduct key={product.id} productData={product}/>) : null}
You need to remove block scope ({}
) around the products.map
call, and don't return empty string ''
in JSX; instead return null
.