What is the process for setting up a "Highlight tab" feature in Next.Js?

I am currently working on implementing a selected tab feature in Next.Js.

Users will have the ability to search for either Users or Posts by clicking on corresponding buttons. https://i.sstatic.net/mRBgQ.png

Once the user clicks on a button, it should change to a blue background indicating it has been selected. https://i.sstatic.net/cbTDA.png

However, I am facing issues where the selected button is not rendering the CSS properly even though the .Selected class is being added to it.

import React, { MouseEventHandler, ReactElement, useState } from 'react'
import { PageWithLayout } from '../components/Layouts/LayoutConfig'
import MainLayout from '../components/Layouts/MainLayout'

import style from '../styles/Search.module.css'

const Search: PageWithLayout = () => {
  const [searchPosts, setPostsSearch] = useState < String > ();

  const setSearchOption = (searchFor: String) => {
    let searchOption = '';

    if (searchFor == 'POSTS') {
      searchOption = 'POSTS';
    } else {
      searchOption = 'USERS';
      let button = document.getElementById('usersOption') as HTMLElement;
      button.className += style.Selected;
    }

    console.log(searchOption);
    setPostsSearch(searchOption);
  }

  return (
    <>
      <div className='pageContent'>
        <div className={style.SearchBarContainer}>
          <div className={style.SearchContainer}>
            <i className="fa-solid fa-magnifying-glass"></i>
            <input className={style.SearchBar} type={'text'} placeholder='Search...' />

          </div>
          <div className={style.SearchOptions}>
            <button id='usersOption' onClick={() => setSearchOption('USERS')}>Users</button>
            <button id='postsOption' onClick={() => setSearchOption('POSTS')}>Posts</button>
          </div>

        </div>
        <div className='SearchedContent'>

        </div>

      </div>
    </>
  )
}

Search.getLayout = function getLayout(page: ReactElement) {
  return (
    <MainLayout>
      {page}
    </MainLayout>
  )
}

export default Search

Answer №1

Utilize the searchOption data to apply className styling

import React, { MouseEventHandler, ReactElement, useState } from 'react'
import { PageWithLayout } from '../components/Layouts/LayoutConfig'
import MainLayout from '../components/Layouts/MainLayout'

import style from '../styles/Search.module.css'

const Searching: PageWithLayout = () => {

    const [searchResults, setSearchResults] = useState<String>();


    return (
        <>
            <div className='pageContent'>
                <div className={style.SearchBarContainer}>
                    <div className={style.SearchContainer}>
                        <i className="fa-solid fa-magnifying-glass"></i>
                        <input className={style.SearchBar} type={'text'} placeholder='Search...'/>

                    </div>
                    <div className={style.SearchOptions}>
                        <button id='usersOption' className={searchResults === 'USERS' ? style.Selected : undefined } onClick={() => setSearchResults('USERS')}>Users</button>
                        <button id='postsOption' className={searchResults === 'POSTS' ? style.Selected : undefined } onClick={() => setSearchResults('POSTS')}>Posts</button>
                    </div>

                </div>
                <div className='SearchedContent'>

                </div>

            </div>
        </>
    )
}

Searching.getLayout = function getLayout(page: ReactElement){
    return(
        <MainLayout>
            {page}
        </MainLayout>
    )
}


export default Searching

Answer №2

It is recommended to maintain a state for the active search option and dynamically apply the class directly in the JSX based on certain conditions.

const [activeSearchOption, setActiveSearchOption] = useState('USERS')

return (
        <>
          <div className='pageContent'>
            <div className={style.SearchBarContainer}>
              <div className={style.SearchContainer}>
                <i className="fa-solid fa-magnifying-glass"></i>
                <input className={style.SearchBar} type={'text'} placeholder='Search...'/>
               </div>
                <div className={style.SearchOptions}>
                  <button id='usersOption' className={activeSearchOption === 'USERS' ? 'active' : ''} onClick={() => setSearchOption('USERS')}>Users</button>
                   <button id='postsOption' className={activeSearchOption === 'POSTS' ? 'active' : ''} onClick={() => setSearchOption('POSTS')}>Posts</button>
                </div>
              </div>
                <div className='SearchedContent'>

                </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

TSLint is encountering the error code TS2459: The module "@azure/core-tracing" claims to have a local declaration of "Span" but does not export it, along with additional errors

I'm completely lost on how to tackle this error. The message I'm getting doesn't provide much insight, other than indicating an issue with the installation of '@azure/ai-text-analytics'. I've gone through the process of uninst ...

Experimenting with code within a window event listener function

I have a component in my AngularJS application that is functioning correctly. However, when it comes to test coverage, everything after the 'window.addEventListener('message',' part is not being covered. Should I create a mock object f ...

Message within the boundary of the input field

Click here to view the image It would be great to have the text "text name" displayed on the border of the input box. Here is the HTML code - <input type="text" id="text creator" class="form-control" placeholder="text creator" na ...

Incorporate new class into preexisting modules from external library

I am currently working on expanding Phaser by incorporating a new module called Phaser.Physics.Box2D. While Phaser already utilizes this module internally, it is an additional plugin and I am determined to create my own version. TypeScript is the language ...

Oops! It seems like there's a problem with reading the 'strEmail' property of undefined. Do you have any ideas on how to fix this issue

Currently, I am working with Express.js to create a straightforward login post request. Here is the code snippet: app.post("/login", (req, res) => { res.send( { isUserRegistered: userLogin(req.body.strEmail, req.body.strPassword), ...

developing a dropdown menu feature

I'm struggling with a small issue related to my drop-down menu function. My goal is to hide the visibility of a menu tab after it has been clicked for the second time. Below is the code snippet I've been working on: HTML:- <nav class="clea ...

React - The previous condition is maintained when selected

A few days back, I encountered a perplexing issue and sought help by posting a question regarding obtaining an index of values. To my relief, I received a reliable answer that enabled me to successfully tweak my existing code. One problem that arose was w ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...

Wait until the link is clicked before showing the list element

Is there a way to prevent the display of list element id="two" in the code below until link "#two" has been clicked, removing element id="one"? I am looking for a CSS or JS solution that completely hides the list element rather than just hiding it from vie ...

The loading button nested inside a server component does not appear in Next.js version 14 client component

Hey everyone, I'm currently working on developing a booking application using Next.js version 14. In this project, I have a route called /search-result that displays all the events fetched from the backend as a server component. Within this page, I am ...

What is the best way to trigger the download of an image file created by PHP to a user's computer?

My PHP code (upload.php) allows users to upload an image from index.html, resize it, add a watermark, and display it on the same page. Users can download the watermarked image by using the 'Save image as...' option. The resized image is saved in ...

What are the benefits of implementing a hexadecimal strategy in javascript?

I have a somewhat unusual question that has been puzzling me. I've noticed some interesting choices in naming variables in JavaScript, seemingly using what appears to be "a hexadecimal approach". For example, I see variables named like _0x2f8b, _0xcb6 ...

Obtain the Zero-width non-joiner character (‌) using the innerHTML attribute

I am attempting to retrieve a &zwnj; using the innerHTML method The desired output should be This section contains a zero-width‌&zwnj;non-joiner, a non-breaking&nbsp;space &amp; an ampersand However, the current output is: This part c ...

Place each label and input element on a separate line without using div tags

Can we separate form elements onto individual lines without enclosing them within divs? For example: <label for="one">One:</label> <input type="text" id="one"> <label for="two">Two:</label> <select id="two"> ...

JavaScript code often contains dates that are formatted in various ways

I need to perform validation in JavaScript by comparing DATES and TIME. I need to have the date in dd/MM/yyyy format, but I am unsure of the format it is currently taking. After debugging the JavaScript code, I discovered the format. The screenshot below ...

Best approach for retrieving and adding a large number of images when dealing with slower connections

Currently, I am retrieving 100-200 images using a combination of ajax-php-mongodb. The process involves ajax making an initial call with parameters, php on the server side locating the appropriate mongo document containing all image file ids in grid fs, fe ...

Generating a unique user ID similar to Zerodha's user ID using Node.js/JavaScript

For a project I'm working on, I need to create random and unique User IDs. I came across Zerodha's user IDs which are easy to remember. In Zerodha user IDs: The first two characters are always letters followed by four numbers. I want to generat ...

What iOS Printing and HTML formatter should you use and what level of sophistication is best?

Currently, I have successfully created an iOS 5 application that sends a job to the print queue. The functionality works fine and utilizes the UIMarkupTextPrintFormatter to generate the document in HTML format. At this point, I am using a simple HTML str ...

What steps should I follow to integrate the NextUI Tab component in my NextJS project?

Hi everyone, I am new to NextJS. I recently set up a basic NextJS starter project with NextUI by using the command npx create-next-app -e https://github.com/nextui-org/next-app-template. Now, I am trying to add a tab group with 3 tabs to the default page. ...

Seems like ngAfterViewInit isn't functioning properly, could it be an error on my end

After implementing my ngAfterViewInit function, I noticed that it is not behaving as expected. I have a hunch that something important may be missing in my code. ngOnInit() { this.dataService.getUsers().subscribe((users) => {this.users = users) ; ...