Home > Software engineering >  How to use if statement inside React JSX loop/map
How to use if statement inside React JSX loop/map

Time:06-02

I'm trying to output two different versions of some HTML inside a React component based on an if statment, this is how I think it should look but the syntax is not right. I am trying to add "active" Breadcrumb.Item if the value of breadCrumbLink.IsActive is true.

{breadCrumbData.BreadCrumbLinks.map(breadCrumbLink => (

if (breadCrumbLink.IsActive == true)
{
    <Breadcrumb.Item key={breadCrumbLink.Id} className="active">
        {breadCrumbLink.LinkText}
    </Breadcrumb.Item active>

}
else
{
    <Breadcrumb.Item key={breadCrumbLink.Id} className="active">
        {breadCrumbLink.LinkText}
    </Breadcrumb.Item>
}

))}

CodePudding user response:

You don't need to render conditionally. Use the condition inside the active property (and inside className if you need):

{breadCrumbData.BreadCrumbLinks.map(breadCrumbLink => 
    (
        <Breadcrumb.Item key={breadCrumbLink.Id} className="active" active={breadCrumbLink.IsActive}>
            {breadCrumbLink.LinkText}
        </Breadcrumb.Item>
    )
)}
  • Related