Modify the text style on the fly using React js

Looking to update the styling of the tab text in the navbar, as well as implement functionality where clicking on a tab switches between pages and marks the selected tab as active. Below is the code I've written:

Header.js

import React from "react";
import "./Header.css";
import Tab from "./Tab";

 const tabs = ["About", "Portfolio", "Blogs", "Contact"];

const Header = () => {
  const 
  return (
    <div className="header">
      {tabs.map((elem, indx) => {
        return <Tab key={indx} text={elem} />;
      })}
    </div>
  );
};

export default Header;

Header.css

.header {
  width: 100%;
  background-color: transparent;
  z-index: 1;
  color: white;
  padding: 1em;
  box-shadow: 2px 2px 2px 2px rgb(66, 65, 65);

  display: flex;
  gap: 2em;
  justify-content: flex-end;
}

Tab.js

import React, { useState } from "react";
import "./Tab.css";

const Tab = ({ text }) => {
  const [active, setActive] = useState(false);

  return (
    <div className="tab">
      <div
        className={`text ${active && "active"}`}
        onClick={() => setActive(true)}>
        {text}
      </div>
    </div>
  );
};

export default Tab;

Tab.css

.tab {
  padding: 0.3;
}

.text {
  font-size: 1.1rem;
}

.active {
  color: chocolate;
  border-bottom: 1px solid chocolate;
}

.text:hover {
  color: chocolate;
  cursor: pointer;
}

Currently, when clicking on a tab it becomes active, but selecting another tab also activates both. I'm seeking guidance on modifying the code to ensure only one tab is active at a time. How can this be accomplished?

Answer №1

To transfer the active tab state from the Tab component to the Header component, create a callback function in the Header component that updates the state when called by the Tab component.

Your final code should look something like this:

const tabs = ['Home', 'Products', 'Services', 'Contact']

const Header = () => {
  const [activeTab, setActiveTab] = useState('');
  
  const handleTabClick = useCallback((tab) => {
    setActiveTab(tab);
  }, []);
  
  return (
    <div className="header">
      {tabs.map((elem) => {
        return <Tab key={elem} text={elem} isActive={elem === activeTab} onTabClick={handleTabClick} />;
      })}
    </div>
  );
}

const Tab = ({ text, isActive, onTabClick }) => {
  return (
    <div className="tab">
      <div
        className={`text ${isActive && "active"}`}
        onClick={() => onTabClick(text)}
      >
        {text}
      </div>
    </div>
  );
}

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

Using Javascript to modify file permissions in Google Drive

I'm new to writing and seeking amazing solutions for all the issues I encounter. I have a website hosted on Google Drive, utilizing its SDK for Javascript. Everything functions exceptionally well, except for one problem. I need to adjust the permissi ...

Struggling with applying mixins

Is it possible to select only the top border using this mixin? Currently, I only need a top border but would like to have the option to use others in the future. Using separate mixins for each side of the border seems inefficient. .bordered(@top-width: 1 ...

What is the best way to create a unique page transition animation using Framer Motion and Next.js?

I am currently using Next.js, React, TypeScript, and Framer Motion in my project. I have successfully implemented page transitions from right to left when changing pages within my _app.tsx file. However, I am facing an issue with the arrow navigation; both ...

An alternative to PHP's exec function in Node.js

I am interested in developing a piece of software using C (such as prime number factorization) and hosting it on my web server with Node.js. Following that, I would like to create an HTML document containing a form and a button. Upon clicking the button, ...

JavaScript Calendar lacks two days

I'm currently developing a custom calendar application using Javascript with Vue JS. One of the methods I've created is for getting the number of days in a specific month: daysInYearMonth(y,m){ return new Date(y, m, 0).getDate() } When I log ...

What is the method for setting a cell's row-span to 2 using bootstrap?

Is there a way to make the red cell in a Bootstrap grid have a row-span=2 and fill the second row as well? .cell {height: 100px; border: 1px solid; border-collapse:collapse;} .red {background: red;} .yel {background: lightyellow;} <link href="https:/ ...

How can you selectively conceal the nth item in a v-for loop while keeping the original array intact? Discover a way to do this using the search function

I have a reference variable called foxArticles that holds a list containing 100 items. Using a v-for loop, I iterate over each value and render all 100 values on the page. <template> <div class="news_container"> <div v- ...

Rendering an image on the HTML5 canvas

I really want my image to be in the perfect spot. I already have this code set up, but how can I adjust the positioning of my image? Whether it's a little to the left or more to the right, I'm talking about the exact coordinates. Where do I need ...

Is there a way to exclusively utilize CSS in order to achieve bottom alignment for this btn-group?

I currently have a series of div elements that I transformed into two columns. https://i.stack.imgur.com/xG7zT.png My goal is to align the PDF/XML button group at the bottom, creating a layout like this: https://i.stack.imgur.com/ijtuH.png This is an e ...

Pseudo-class for clicking a button on Mobile WebKit

Currently, I am in the process of developing a private framework to replicate the iOS UI using CSS 3 and HTML 5. Most of the widgets have been created, including various colored gradient buttons, but faced with challenges when attempting to incorporate a b ...

Exploring ways to integrate Javascript and CSS into a Bootstrap lightbox modal dialog?

Can someone help me figure out how to use the bootstrap lightbox to display a form with specific CSS style and JavaScript code for the form? I'm having some trouble implementing it. I specifically need this setup because I am using Selectize.JS to cr ...

When combining Puppeteer with Electron, an error stating "Browser revision not found" may occur. However, this issue does not arise when running with Node

My attempts to make Puppeteer work in Electron have been with various versions of Puppeteer (v5.4.0, v5.4.1, and v5.5.0), on Windows 10/MacOS, and with different Node versions (v12, v14.0.1, v15.0.3). Trying a simple puppeteer.launch() in the main process ...

A router that has numerous parameters will not function properly with express.static

I successfully created an express router with the parameter 'router.get('/add')' and it is working perfectly. However, when I added 'router.get('/edit/:id')', the express.static feature stopped working, causing issue ...

Comparing React's Styled-components, JSS, and Emotion: Which is

As a CTO, I am faced with the decision of choosing between three popular CSS-in-JS libraries: jss emotion styled-component. I will keep this question focused and avoid straying into subjective territory. If necessary, I will answer it myself by asking sp ...

Unique style CSS (Flex)Grid with spacing and uniform aspect ratio

Hello everyone, typically I'm quite skilled when it comes to CSS but this particular challenge has pushed me to my limits. I have a desire to create a grid where all elements maintain the same aspect ratio (with images that already share this aspect ...

What is the best way to match the minimum height of one div to the height of another div?

I need to dynamically set the minimum height of #wrapper equal to the height of #sidebar, but the height of #sidebar is not fixed. Here is my attempt at achieving this with JavaScript: var sidebarHeight = jQuery('#sidebar').height; jQuery(&apos ...

Establish a connection between the Discord Bot and a different channel

I need help with my Discord bot that should redirect someone to a different channel when they mention certain trigger word(s). I feel like there might be a missing line or two of code that I need to add to make it work properly. bot.on("message", messag ...

The phonegap page redirection is failing, as the 'location' property of the object does not function correctly

I'm attempting to implement a straightforward page redirection in PhoneGap using JavaScript. Within an iframe, I have the following code: window.parent.location("event_select.html"); Unfortunately, this approach is unsuccessful and results in the fo ...

Using the OR operator in an Angular filter

How can I create a filter with a range slider that shows multiple categories when it's in a certain position? I have tried using the code below to filter based on the range, but it only captures the first word after the OR operator. Can anyone provid ...

Guide on implementing a filter on an image using P5 in a React application

Seeking clarity on a specific issue, I'm using a react-P5-wrapper to create my P5 canvas in React, and I want to apply a filter to an image. Typically, in P5, this would be done with image.filter(GRAY). However, when P5 is an instance in React, I can& ...