Reactjs - Multiple If Conditions Inside Map Function

Reactjs - Multiple if conditions inside map function

{item.venue.price.tier === 1 && <span className="percentage one"></span>}

If/else statements don't work in JSX, because of how the 'language' is designed to make calls / construct objects. This is how to achieve conditional rendering.

Bear in mind also that you will also have to return just one element. So you will have to group the latter options like so:

<div>
<span className="percentage one"></span>
<span className="percentage two"></span>
<span className="percentage three"></span>
<span className="percentage four"></span>
</div>

Multiple ternary operators inside a single .map() in React JS

If you refactor it in this way it should work and it is cleaner way of doing conditional rendering in react

 {move?.past_values?.map((mp) => 
<>
{mp?.power !== null &&
<li>Before {mp?.version_group?.name} : {mp?.power}</li>}

{mp?.accuracy !== null &&
<li>Before {mp?.version_group?.name} : {mp?.accuracy}</li>} )
</>
}

Reactjs condition inside map function

Issues:

1- Use {} to put expressions inside jsx (to put map inside div).

2- you are using {} means block body of arrow function, so you need to use return inside the function body, otherwise by default map returns undefined.

3- You are using {} twice, so 2nd {} will be treated as object and content.type will be treated as key and that key is not valid, thats why you are getting error.

4- Forgot to define the key on elements.

Use this:

return (
<div>
{
props.content.map(content => content.type === "card" ? (
<Card title={content.title} />
) : (
<Content title={content.title} paragraph={content.guideline} />
)
)}
</div>
);

If condition inside Map // React JS

You can also use if-else block like this in react and return jsx from if-else block.

const items = [
{to: '/link1', label: 'Step 1', stepClass: 'active'},
{to: '/link2', label: 'Step 2', stepClass: 'inactive'},
];

<Breadcrumb>
{items.map(({to, label, stepClass}) => {
if(stepClass === "inactive")
{
return (
<Link key={to} to={to}>
<div className={`step ${stepClass}`}>{label}</div>
</Link>
);
}
else
{
return (

// code here
);
}

})}
</Breadcrumb>

How to conditional render inside map in a functional component of react js

You are not returning anything from the 'map' function.

resp_data.map((item) => (
item.looking_for === "work" ? (
<div className="card-rows work" key={item.id}>
work
</div>
) : (<div className="card-rows no_work" key={item.id}>
No work
</div>)
)
)

multiple if statements in a React.js component

This part...

if (sortBy === 'true' || 'false') {
//...
}

...should be...

if (sortBy === 'true' || sortBy === 'false') {
//...
}

You didn't check the condition if sortBy equals 'false' but you checked the value 'false' itself. This will return true because the string 'false' is truthy.

So currently both of your if statements are true and are executed.



Related Topics



Leave a reply



Submit