What is the best way to apply a unique style to the currently active tab in a sidenav based on

I am in the process of creating a side navigation bar where I want to incorporate a left border on the active tab. How can I achieve this by utilizing state and passing a boolean value as a prop to the Child SideNavItem class, then updating it with each tab change?

Here is the code snippet for the parent SideNav component: Currently, I am using an if-else statement to determine the current location and pass it as a prop to the Child class. However, at the moment, both the Home and My Profile tabs are displaying the side border.

import { NavLink } from "react-router-dom";
import SideNavItems from "./SideNavItems";
import React, {useState} from 'react';

// Rest of the code remains as is...

const SideNav = (): JSX.Element => {
  let [active, setActive] = useState(true);
  let isActive = (currentPath: any, thisPath: any) => {
    if (currentPath===thisPath) {
      setActive(true)
    } else {
      setActive(false);
    }
    return active;
  }
  const resetState = () => {
    setActive(false);
  };
  return (
    <div className="sidebar mt-5">
      // Rendered NavLinks and SideNavItems components
    </div>
  );
};

export default SideNav;

And here is the updated code for the Child Class:

import React from "react";

type Props = {
  active: any;
  text: string;
  icon: any;
};
const SideNavItems: React.FC<Props> = ({active, icon, text }) => (
  <div className={`flex items-center cursor-pointer hover:text-red-400 transition duration-100 ease-in-out ${active ? ` text-red-400 border-l-4 border-red-400` : ``}`}>
    // Displaying icon and text elements with conditional CSS classes
  </div>
);

export default SideNavItems;


Answer №1

The source of the confusion you're encountering here stems from the fact that invoking setActive within the isActive function does not immediately update the value of the active variable. Consequently, when you promptly return the active variable, you are essentially returning its previous value instead of the intended one.

In reality, it is likely unnecessary to store the value of active in a component state variable:

const SideNav = (): JSX.Element => {
  return (
    <div className='sidebar mt-5'>
      <div className='logo ml-2'>
        <img alt='logo' src={require('../assets/images/logo.png').default} />
      </div>
      <NavLink to='/'>
        <SideNavItems
          active={window.location.pathname === '/'}
          icon={HomeIcon}
          text={'Home'}
        />
      </NavLink>
      <NavLink to='/profile'>
        <SideNavItems
          active={window.location.pathname === '/profile'}
          icon={ProfileIcon}
          text={'My Profile'}
        />
      </NavLink>
      <SideNavItems active={''} icon={PointIcon} text={'Daily Points'} />
      <SideNavItems active={''} icon={SupportIcon} text={'Support'} />
      <SideNavItems active={''} icon={ContributeIcon} text={'Contribute'} />
    </div>
  );
};

export default SideNav;

If you are utilizing react router, consider employing the useLocation hook to ensure that the component re-renders whenever the path changes:

import { useLocation } from 'react-router-dom';

const SideNav = (): JSX.Element => {

  const { pathname: currentPath } = useLocation();

  return (
    <div className='sidebar mt-5'>
      <div className='logo ml-2'>
        <img alt='logo' src={require('../assets/images/logo.png').default} />
      </div>
      <NavLink to='/'>
        <SideNavItems
          active={currentPath === '/'}
          icon={HomeIcon}
          text={'Home'}
        />
      </NavLink>
      <NavLink to='/profile'>
        <SideNavItems
          active={currentPath === '/profile'}
          icon={ProfileIcon}
          text={'My Profile'}
        />
      </NavLink>
      <SideNavItems active={''} icon={PointIcon} text={'Daily Points'} />
      <SideNavItems active={''} icon={SupportIcon} text={'Support'} />
      <SideNavItems active={''} icon={ContributeIcon} text={'Contribute'} />
    </div>
  );
};

export default SideNav;

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

Parsing improperly formatted JSON from an HTTP GET request can be done using either AngularJS or JQuery

Trying to decipher a poorly formatted JSON response from a remote server that looks something like this: //[ {},{} ] In my AngularJS code: $http.get('http://www.example.com/badjson') .success(function(data) { console.log(data); }) ...

Ways to display pre-selected information using MUI datagrid's checkboxSelection feature

I am currently working on a React web application and using a DataGrid component. I need to have certain rows pre-selected in the DataGrid just like they were selected previously by the user. https://i.sstatic.net/1iILu.png At the moment, the user has acc ...

Challenges with JSON Documents

const fs = require('fs'); const express = require('express'); const app = express(); app.use(express.json()); app.get('/submit', (req, res) => { let Com_Title = req.query.ComTitle; let Com_Text = req.query.ComTex ...

Is there a way to take a snapshot of an HTML Canvas frame and showcase it on a Bootstrap modal?

I have a page where users must grant permission for their webcam or camera. Once granted, a webmoji will move according to the user's face position. Below is a button that will turn blue and become active once a face is detected. When clicked, I want ...

Arrange two divs next to each other on the page: the div on the right can be scrolled through, while the div on the

I am attempting to create a layout similar to this https://i.sstatic.net/Y1FCp.png My goal is to: Have two main divs positioned side by side inside a wrapper div Ensure the wrapper expands to fill 100% of the browser size The left div (banner) should b ...

Accessing firebase using a connection to HTML5 through codeanywhere's devbox

Recently, I added Firebase to my CodeAnywhere HTML5 connection. However, when I tried to execute the shell command firebase login, I was directed to a URL to log in. Despite successfully logging in and granting the necessary permissions, I encountered an e ...

Leverage the calc() function within the makeStyles method

const useStyles = makeStyles((theme) => ({ dialog: { '& .MuiTextField-root': { margin: theme.spacing(1), } }, address: { width:"calc(24vw + 8px)" }, })); <div> <TextField id="contact ...

What is the best way to adjust text across several lines to perfectly fit within a div's width?

http://codepen.io/anon/pen/oXGMQZ Is there a way to automatically adjust the font size of each span within a parent div so that it fills the width of the parent div? <div class="box"> <span class="fit">what</span> <span class="fi ...

Methods for maintaining accuracy when updating a user's follower count using Node.js with MongoDB

In my latest project, I am developing a social API system that allows users to follow and unfollow each other. The user model I currently have set up looks like this: sourceId: { type: Schema.Types.ObjectId, ref: "user", required: t ...

Only line breaks are permitted in Mustache.js, all other HTML characters are escaped

After a user submits input, I am generating comments and displaying them using Mustache.js. When it comes to rendering the comments, I have found that replacing user-entered line breaks (\n) with <br/> allows them to display as HTML breaks. To ...

Tips for reducing button spacing and editing pages without using an ID in the URL in Admin-on-rest

Recently, I delved into the world of admin-on-rest and I'm really impressed with its capabilities. However, I've hit a roadblock with two specific issues and would greatly appreciate some guidance: Issue 1 After creating a custom theme complete ...

Expand the background of columns to cover grid gutters

Imagine this... You're working on a layout with three columns, all within a fixed-sized container that is centered using margin:0 auto. The design requires the first column to have a background color that reaches the left edge of the browser window. ...

The submit button is unable to initiate the ajax function

I encountered an issue with my code while attempting to separate my form function into a different PHP file and utilize an Ajax function to call the form based on the IDs. However, after separating the form function, the submit button no longer triggers th ...

Input tag styled in a center-aligned word document format

My Desired Text Alignment: I want the text to be centered horizontally at the top of the input. Words should break after hitting the internal padding, similar to how document creation software like Google Docs works with center alignment. Current Alignme ...

A straightforward development and production build to incorporate HTTPS for a static website created with React and Express

Is there a straightforward method to create a static web page and Node backend where the Node server runs in HTTPS during development but not in production? How can the static web page point to https://localhost/foo in dev mode, and simply /foo in producti ...

Updating state in a component based on changes in propsWould you

My component is linked to the Redux store to retrieve data from props: const mapStateToProps = state => ({rowData: dataSelector(state)}) Aside from props, the component also has its own state: this.state = { rowsPerPage: 23, pageCount: 0, } I am ...

Why are my images only 1 pixel tall in Internet Explorer 8?

<img src="blah.png" width="150" height="auto"> When viewed in Firefox, Chrome, or Safari, the image will appear as intended. However, Internet Explorer may cause the image to display at a height of only 1 pixel while maintaining the width of 150 pix ...

Picture in the form of a radio button

Is there a way to use an image instead of a radio button in my AngularJS form? I have managed to hide the radio button using CSS, but it disables the checked event. How can I make the image clickable? position: absolute; left: -9999px; Here is the code s ...

Browserify - combine external modules into a single bundle

I am a complete beginner in the world of browserify. I recently discovered this interesting module called peer-file, which allows for file transfer between two browsers. After reading the Usage section in its readme, I realized I needed to include the scri ...

The 'load()' event method in jQuery does not function properly within the 'ready()' event method on mobile browsers

After testing on Firefox mobile and Chrome mobile browsers, I found that my code works perfectly on computer browsers. Below is the code I have inside the ready() and load() event methods: $(document).ready(function(){ $(window).on('load hashchan ...