Styling links conditionally in a React component

How can I style the page title in my nav bar when I am on the selected path? I am using React and Tailwind CSS. For example, I want the title to turn yellow when I am on the current page.

Here is the logic I have tried, but it doesn't seem to be working:

<div className={active ? "text-yellow-400" : undefined}

This is my route code:

const LinkItem = ({href, path, children, ...props}) => {
    const active = path === href
    return (
        <NextLink href={href}>
            <div className={active ? "text-yellow-400" : undefined}
                {...props}
            >
                {children}
            </div>
        </NextLink>
    )
}

Below is the code for my nav bar:

const Navbar = props => {

    const {path} = props

    return (
           <LinkItem href="/page1" path={path}>
               Page 1
           </LinkItem>
           )
}

Answer №1

Instead of using undefined, it is recommended to use either null or an empty string ""

Furthermore, it is advisable to utilize useState (although not necessary in this specific case, it is always good practice) https://reactjs.org/docs/hooks-state.html

Answer №2

After some investigation, I discovered that the issue stemmed from the undefined path variable, causing a mismatch with the href value and thus failing the condition.

To resolve this, I utilized the useRouter hook to retrieve the path using the .asPath parameter, which allowed me to access the parameter stored in my path variable.

Here is the modified code snippet:

import NextLink from 'next/link'
import {useRouter} from "next/router";

const LinkItem = ({href, children, ...props}) => {
    const path = useRouter().asPath
    const active = path === href
    return (
        <NextLink href={href}>
            <div className={active ? "<styles here>" : "<styles here>"}
                {...props}
            >
                {children}
            </div>
        </NextLink>
    )
}

Updated navigation bar code:

const Navbar = props => {

    const {path} = props

    return (
           <LinkItem href="/page1" path={path}>
               Page 1
           </LinkItem>
           <LinkItem href="/page2" path={path}>
               Page 2
           </LinkItem>
           )
}

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

Checking the existence of a user's email in Node.js

Hey there! I am new here and currently learning Node.js with Express. I'm trying to find a way to check if a user's email already exists in the database. Here is what I have so far: const emailExists = user.findOne({ email: req.body.email }); if ...

I am facing an issue where my AngularJS code is not executing properly on JSF

I'm trying to clear the text inside a textarea using AngularJS after typing and clicking on a button. Here's the link to the fiddle for reference: http://jsfiddle.net/aman2690/2Ljrp54q/10/ However, I keep encountering the following error messag ...

Steps for aligning a table in the middle of a webpage

Can someone help me align my table to the center of the webpage? I have tried using align="right" and "center" but neither seem to be working. Any tips on how to position the table correctly? <table style="table-layout:fixed;" align="right" cellspaci ...

Passing a variable by copy in a done call with Ajax

Here's the code snippet I'm working with: for (var i = 0; i < list.length; i++) { $.when( $.ajax({url: "./dorequest.php?id=" + list[i], success: function(response){ jsonFriendlist = response; }}) ).done( ...

Swapping the image source using a Vue dropdown menu

Recently I started using Vue and decided to implement a dropdown menu component (). The component pulls its list items from a JSON array structured as follows: <template> <div id="app"> <div id='container'> ...

Utilizing Stylus: Embracing Interpolation within a Mixin

I am encountering an issue while attempting to interpolate values passed into a mixin. positionModifier( key, x, y) &.{key} background-position: {x}px {y}px; An error is being thrown, which is shown below: 351| positionModifie ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

What is the best way to effectively personalize my Bootstrap variables using SASS?

After creating a web page and adding Bootstrap styling, I attempted to customize the Bootstrap variables, but encountered an issue where it did not seem to work despite no errors being displayed. I followed a tutorial on YouTube meticulously, but to no av ...

What is the process for adding various font weights in styled-components?

Hey there, I'm looking to incorporate different font weights of the Inter font (400, 500, 700) into my project. Currently, it's only loading the Inter regular font. I'm working with create-react-app, TypeScript, and styled-components. Here& ...

The Next.js Hydration process has encountered a failure due to a discrepancy between the initial UI initialization and the server-rendered content

When I try to pull out the mobilesidebar from my code, it shows up as white with no issues. I receive the following message: The exact error message I am seeing Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was ...

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

When the screen size decreases, display the title on two lines

Currently, I am in the process of developing a react web application with the assistance of redux. My main objective is to ensure that the page is highly responsive. At this point, there is a title positioned at the top displaying: Actions to do: Past due ...

Steps for transforming an array of objects into an array of values based on a specific key

Is there a way to extract messages based on keywords from a JSON structure? Here is an example of the JSON structure: [{ _id: 123, message: 'hello', username: '1' }, { _id: 456, message: 'world', username: '2'}] I ...

Retrieving data from a subcollection in a cloud firestore database does not yield any results

In my Next.js application, I am utilizing Cloud Firestore database to store user documents. The structure of the collection path is as follows: collection "userDocs" └─ document "userEmail" └─ collection "docs" └─ document "document ...

Troubleshooting problem with CSS borders in Microsoft Edge Browser

I am currently working on implementing the concept found at the following link: https://www.w3schools.com/howto/howto_js_tabs.asp, but with the additional feature of borders around the elements. However, I have encountered an issue specifically with Micro ...

I am a beginner in the world of MEAN stack development. Recently, I attempted to save the data from my form submissions to a MongoDB database, but unfortunately, I have encountered

const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); const Schema = new mongoose.Schema({ username: St ...

What could be causing the model to not bind correctly in nodejs?

In the process of developing a web app with nodejs, angular, and mongo, I have encountered a strange issue. The model is not binding properly from the JSON object. Here is my Schema: var mongoose = require('mongoose'); var productSchema = new ...

What could be causing my code to lag by 2 ticks instead of just 1?

Apologies for any spacing issues. Player = { move: function(cycle, opponent) { switch(cycle.current_direction) { case 'up': cycle.y -= cycle.height; break; case 'down': cycle.y += cycle.hei ...

What is the best way to incorporate font-awesome icons into a Rails view?

I'm struggling to incorporate font-awesome icons in my Rails view. I had a static standalone HTML code snippet that I added into the Rails view: <span class="icon-white"> <a href="https://twitter.com/xyz"> <i class="icon icon-tw ...

Put a pause on CSS3 animations

I have created a unique CSS3 menu item and I am looking to showcase the articles item in a special way: By clicking on the 4th item, it should display the first one, followed by the second one, then the third with a slight delay of 0.5 seconds between them ...