What is the best way to incorporate an extra CSS class into a React NavLink when a conditional CSS class is already present?

In my React component, I have a NavLink that loads a conditional class when a button is clicked. Here's an example:

<NavLink to='property' className={` ${({isActive}) => isActive ? "property-info-nav-active" : "property-info-nav-link"} property-info-nav-item `}>Property</NavLink>

I am trying to add an additional class outside of the conditional inline function classes, but so far I haven't been successful!

I attempted this, but it didn't work as expected.

<NavLink to='property' className={`${({ isActive }) => (isActive ? "property-info-nav-active" : "property-info-nav-link")} additional-class`}>Property</NavLink>

Below is my complete code snippet:

import { NavLink, Outlet } from "react-router-dom"
import "../index.css";

const LandlordLayout = () => {
  return (
    <>  
        <div className="landlord-properties-menu"> 
            <NavLink to="." end className={({isActive}) => isActive ? "landlord-nav-link-active" : "landlord-nav-link" }>Dashboard</NavLink>       
            <NavLink to="income" className={({isActive}) => isActive ? "landlord-nav-link-active" : "landlord-nav-link"}>Income</NavLink>        
            <NavLink to="properties" className={({isActive}) => isActive ? "landlord-nav-link-active" : "landlord-nav-link"}>Properties</NavLink>                 
            <NavLink to="reviews" className={({isActive}) => isActive ? "landlord-nav-link-active" : "landlord-nav-link"}>Review</NavLink>                
        </div>
        <Outlet/>
    </>
  )
}

export default LandlordLayout

Answer №1

"isActive" needs to be changed to "state."

<NavLink to='property' className={`${state ? "property-info-nav-active" : "property-info-nav-link"} additional-class` additional-class}>property</NavLink>

Answer №2

Instead of using the arrow function, you have the option to utilize a custom function.

function Navigation(isActive) {
    function customFunction(isActive ) {
        return isActive ? "property-info-nav-active" : "property-info-nav-link" + " " +"additional-class"
    }
    return (
        <>
            <div className={customFunction(isActive)}>
                property
            </div>
        </>
    );
}
export default Navigation;

Alternatively, you can use an

Immediately Invoked Function Expression
:

 <div className={((isActive) => (isActive ? "property-info-nav-active" : "property-info-nav-link" + " " + "additional-class" ) )()}>
                property
 </div>

Answer №3

If you want to join multiple classes conditionally, one way is to create a custom function specifically for this purpose.

Here's the definition of a function called "combineClasses":

export function combineClasses(...classNames: any) {
  return classNames.filter(Boolean).join(" ");
}

For example:

<div
className={combineClasses( somearray.length > 0 ? "border border-green-100 text-black-400" : "", "flex items-center")}
onClick={handleClick}
>...</div>

Answer №4

<NavLink to='house' className='house-item-info-nav-link'>house</NavLink>

If a NavLink component is active, it automatically adds an active class for easy styling with CSS.

.house-item-info-nav-link a.active {
     text-decoration: underline;
}

Answer №5

If you need to perform custom actions during an event, consider implementing an event handler. For example, you can change classnames by accessing the 'event.current' property. To learn more about this topic, refer to the following article:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Regarding the current status of React Redux

I'm currently developing a Single Page Application using Redux for state management. The main logic component is connected to the redux store and passes down the 'posts' state as props to its child component. When accessing the posts in the ...

Issue encountered: An unexpected token = error appeared after updating from RN version 0.64.2 to 0.65.1

After upgrading from version 64.1 to 65.1 using the upgrade helper, I encountered an error that has been difficult to resolve. Even after updating node/npm to version 14.17 and trying various other solutions, I have not been able to fix this issue during ...

Trouble with Formik checkboxes updating values

I am currently in the process of creating a form using Formik, which essentially consists of a series of check-boxes. Here is an overview of what I am working on: These are the props that I have: "settings" : { "email_addresses": [ "<a ...

nest <div> elements inside a "row" class using Bootstrap4

I'm looking for a way to position an element inside a row class. Check out the JS Fiddle link: https://jsfiddle.net/jLhvmq24/2/ The small tag "Enter Business Email" needs to be displayed below the input box. <div class="row"> <div class= ...

React Ag-Grid Material UI Integration

Are there any standout instances of incorporating AgGrid with React Material UI, particularly when it comes to developing custom themes? The examples provided on the AgGrid website focus on css/scss rather than styled components, which are the preferred ...

What approach do you recommend for creating unique CSS or SCSS styles for the same component?

Consider a scenario where you have a complicated component like a dropdown menu and you want to apply custom styles to it when using it in different contexts. This customization includes not only changing colors but also adjusting spacing and adding icons. ...

Using the class for jQuery validation as opposed to the name attribute

I am looking to implement form validation using the jquery validate plugin, but I am facing an issue with using the 'name' attribute in the html since it is also used by the server application. Specifically, I want to restrict the number of check ...

python conducting automation tests with Selenium WebDriver on a mouse

Hello, I'm having trouble with opening the Mouser website and using the search bar to send some data. Below is a sample of the code I've been working on, but I can't seem to find the correct CSS selector. Any help would be greatly appreciate ...

As jQuery animates, the navigation bar gracefully descends

I've been immersing myself in learning HTML, CSS, and jQuery for the past ten days. Building my first website has been a fun challenge, allowing me to experiment with different elements. One of my recent experiments involved creating an animation for ...

Changing color of entire SVG image: a step-by-step guide

Check out this SVG image I found: https://jsfiddle.net/hey0qvgk/3/ <?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1" width="90" height="9 ...

The color of ngClass does not update according to the variable's value

When the value is true, I want to display a green text message and when it's false, I want it to be red. This is my angular app: In the controller, I declare a variable at the beginning and set it as true: $scope.IsColor = true; if (response.data.i ...

unable to scroll to the bottom of a div after receiving new data through ajax requests

I'm having an issue with a div that has a scrollbar. Initially, the div scrolls to the bottom when loaded. However, after making a post request and loading new ajax data, it no longer scrolls to the bottom properly. It seems to be going to the "previo ...

What is the new Bootstrap equivalent for btn-group-justify?

Could someone help me align the 3 radio options in this HTML code to make them appear justified? I have already tried using d-flex and btn-group-justify without success. If anyone could provide a sample using only Bootstrap 4.1+, it would be greatly appre ...

Combining React-Redux and Bootstrap: A sophisticated modal feature

Struggling with the distinction between components and containers when using Bootstrap's modal in React-Redux. Instead of repetitively creating modals, I aim to develop a React Component that encompasses a modal template. For clarification, here&apo ...

Serving static files in Django

Currently diving into Django and encountering a hurdle with static files. I've followed the setup in both the settings and HTML, but unfortunately, they are not loading on the website. Seeking assistance to resolve this issue! **settings.py:** STATIC ...

Dark background with Bootstrap 4's blue horizontal line beneath the navbar list

How can I remove the blue horizontal line that is appearing on the navigation bar below the list, creating a separation between two elements against a dark background? I am using Bootstrap 4 but unsure of how or why it appeared there. Additionally, I am st ...

Issue with alignment on the printed version of an HTML document

While attempting to print an auto-generated HTML page through my Thermal POS printer, I encountered a large left margin issue. The application is developed using PyQt5, and I had to resort to a python script to generate the HTML code. Unfortunately, in the ...

How to efficiently pass dynamic props in Next.js persisting layoutuciary

When setting up a persistence layout, I utilize the getLayout function on each page as shown below: import { Layout } from 'hoc'; const Page = () => { return ( <div>hello</div> ); }; Page.getLayout = function getLayout(pa ...

What is the best way to add attribution text to background images in reveal.js?

I am considering using reveal.js for a series of lectures. I would like to include attribution text in a subtle location (bottom right) for any background images on slides. These images are specified using <section background-data="url(...)"> withi ...

Challenges arise when utilizing CSS3 animations in conjunction with transitions triggered by toggling a JavaScript class

Struggling to activate an animation while updating a class using JavaScript for a PhoneGap app. Planning on utilizing -webkit- prefixes for compatibility. However, the animations are currently unresponsive in Chrome during testing, both when applied to th ...