Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
Remove border/style from previously clicked link - React/Nextjs

I have a function that triggers onClick which adds borders to the clicked element.

Here is the code in the component:

import { useEffect, useState } from 'react';

import Link from 'next/link';
import Logo from '../../components/logo.svg';
import React from 'react';
import getConfig from 'next/config';
import { useRouter } from 'next/router';

const {
    publicRuntimeConfig: { domain },
} = getConfig();

export default function MediaNav() {
    // If router equals link in list, show blue border
    const router = useRouter();
    const menu = ['Home', 'FAQs', 'Contact Us', 'Social Media'];
    const [selectedPage, setPage] = useState({
        borderColor: '',
    });

    const handleLinkClick = e => {
        setPage({
            borderStyle: '3px solid #005ba9',
        });
        e.target.style.borderLeft = selectedPage.borderStyle;
        e.target.style.borderRight = selectedPage.borderStyle;
    };

    return (
        <nav>
            <div>
                <Link href={`${domain}`}>
                    <a>
                        <Logo />
                    </a>
                </Link>
            </div>
            <ul
            >
                <div>
                    <ul>
                        <li
                        >
                            <a href="/subdomain/link">All Sites</a>
                        </li>
                    </ul>
                        <ul
                        >
                            {menu.map((item, i) => {
                                return (
                                    <li key={i}>
                                        <Link href={item === 'Home' ? '/subdomain/link' : `/subdomain/${item}`.replace(/\s+/g, '').toLowerCase()}>
                                            <a onClick={handleLinkClick}>
                                                {item}
                                            </a>
                                        </Link>
                                    </li>
                                );
                            })}
                        </ul>
                    ) : null}
                </div>
            </ul>
        </nav>
    );
}

At the moment, when the element in the link list is clicked, the blue border is being applied, however, if I click another link, I wanted the previously clicked element link to be removed its borders.

As this is NextJs and I have a Link tag wrapping up the link element, loading is not occurring, therefore I don't know how to make a difference between previously clicked element and currently clicked element.

Any idea how to remove the borders to already clicked link when next link is clicked?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I think a better approach to this problem would be having a state to save currentPage user visiting and depending on currentPage state giving a style to a element.

import { useEffect, useState } from 'react';

import Link from 'next/link';
import Logo from '../../components/logo.svg';
import React from 'react';
import getConfig from 'next/config';
import { useRouter } from 'next/router';

const {
    publicRuntimeConfig: { domain },
} = getConfig();

export default function MediaNav() {
    // If router equals link in list, show blue border
    const router = useRouter();
    const menu = ['Home', 'FAQs', 'Contact Us', 'Social Media'];
    const [currentPage, setCurrentPage] = useState('')

    const handleLinkClick = pageName => {
        setCurrentPage(pageName);
    };

    return (
        <nav>
            <div>
                <Link href={`${domain}`}>
                    <a>
                        <Logo />
                    </a>
                </Link>
            </div>
            <ul
            >
                <div>
                    <ul>
                        <li
                        >
                            <a href="/subdomain/link">All Sites</a>
                        </li>
                    </ul>
                        <ul>
                            {menu.map((item, i) => {
                                return (
                                    <li key={i}>
                                        <Link href={item === 'Home' ? '/subdomain/link' : `/subdomain/${item}`.replace(/\s+/g, '').toLowerCase()}>
                                            <a onClick={() => handleLinkClick(item)} style={{ border: currentPage === item ? '3px solid #005ba9': 'initial' }}>
                                                {item}
                                            </a>
                                        </Link>
                                    </li>
                                );
                            })}
                        </ul>
                </div>
            </ul>
        </nav>
    );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I think instead of adding a style on a target element, you can try adding a class, let's say highlight on the element.

highlight class would look like -

.highlight {
     border-left: '3px solid #005ba9',
     border-right: '3px solid #005ba9'
}

So only the elements which have this class would show the border styles applied. Since the components would re-render on state changes, make sure you are applying the highlight class on the link in map function logic. This would ensure other elements won't have this class and this would solve the problem.

PS: Removing of the previously applied styles would be tedious. I think the above solution would work without much hassle and it would work great.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda