Styling an active link in Next.js using Styled Components

Looking for a way to customize the active link style using styled components.

I have a navigation bar where the currently active link should have a specific style applied.

Any suggestions are appreciated!

import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { bool } from 'prop-types';
import StyledSidebar from '../../styles/header/styled.sidebar'
import StyledLink from '../../styles/header/styled.links'


export default function Sidebar({ open }) {
    const router = useRouter()

    return (
        <StyledSidebar open={open}>
            <div>
                <ul>
                    <StyledLink><Link href="/" className={router.pathname == "/" ? 'active' : ''}>HOME</Link></StyledLink>
                    <StyledLink><Link href="/destination" className={router.pathname == "/destination" ? 'active' : ''}>DESTINATION</Link></StyledLink>
                    <StyledLink><Link href="/crew" className={router.pathname == "/crew" ? 'active' : ''}>CREW</Link></StyledLink>
                    <StyledLink><Link href="/technology" className={router.pathname == "/" ? 'active' : ''}>TECHNOLOGY</Link></StyledLink>
                </ul>
            </div>
        </StyledSidebar>
    )
}

Sidebar.propTypes = {
    open: bool.isRequired,
};


Answer №1

Take a look at this https://codesandbox.io/s/exciting-kilby-eb3pj?file=/src/App.js:0-584 URL to witness this logic in action

Send the props to styled-components as regular props restructuring and utilize them to conditionally apply styles

import styled, { css } from "styled-components";

// Destructure received props
const Button = styled.button(
  ({ someprops }) => css`
    ${console.log(someprops)}
    font-size: 1em;
    margin: 1em;
    padding: 0.25em 1em;
    border-radius: 3px;
    // Conditionally apply styles inside the style
    color: ${someprops === "root" ? "red" : "green"};
    border: 2px solid ${someprops === "root" ? "red" : "green"};
  `
);

export default function App() {
  return (
    <div>
      <Button someprops="root">Themed</Button>
    </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

Steps to close a socket upon session expiration

I am currently working on a small express application that also incorporates a socket program. Everything works perfectly when a user successfully logs in - it creates the session and socket connection seamlessly. However, I encountered an issue where eve ...

Having difficulty grasping the concept behind the prepend method's functionality

I encountered an issue with my code, where I successfully created a <th> element initially, but faced problems when trying to create it repeatedly. function createTH(){ var noOfRow = document.getElementById("addItemTable").rows.length; var t ...

Using the ES6 filter method to iterate through a double nested array of objects

Struggling with filtering a nested array of objects and specifically stuck at the filter part. Any idea on how to eliminate one of the marks? this.state = { data: [ { id: 1, name: "Main", subs: [ { id: "jay", ...

React.js mouse and touch events do not function properly when on a mobile device's screen

View React, javascript, CSS codes for this issue I encountered some problems with my codepen codes. The code is too long to paste here, so I have included a snippet below. You can view the full code and output screen by clicking on the link below: View O ...

Connect a responsive div to a main div

I'm relatively new to the world of Javascript, CSS, and HTML. Currently, I'm attempting to anchor a div to the center and bottom of its parent div. The parent div contains a responsive background image and my fa fa-arrow icon is correctly positi ...

Retrieve the initial value from the TextField

My website features multiple filters, including by date and duration, allowing users to easily find the information they need from a large dataset. There is also a "reset all filters" button that clears all filters and displays the full list of products. ...

Express.js and Node version 0.10.29: The Mystery Post

Having trouble with sending JSON data to an express server and receiving 'undefined' for req.body.name. This is how the configuration is set up: const express = require('express'); const app = express(); app.configure(function(){ ...

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...

Unable to trigger jQuery .click event

Having recently delved into the world of AJAX, jQuery, and JavaScript, I am facing a challenge that I believe is rooted in a simple oversight on my part. Expressing this issue can be quite perplexing, but I'll do my utmost to articulate it clearly. I ...

Automatically updating a database value in CodeIgniter after a countdown has expired

I am looking to automatically update a value in my MySQL database using CodeIgniter once a countdown timer reaches zero. However, I am struggling to figure out how to implement this. Here is an example: I have a database structured like this: [image lin ...

Initiate the command with given parameters

Currently, I am utilizing a combination of React, Redux, Rxjs, typesafe-actions, and TypeScript to invoke an action with parameters. Here is my current code: Actions: import { createAsyncAction } from 'typesafe-actions'; import {ICats} from &ap ...

Tips on creating a script for detecting changes in the table element's rows and columns with the specified data values

I have a div-based drop-down with its value stored in TD[data-value]. I am looking to write a script that will trigger when the TD data-value changes. Here is the format of the TD: <td data-value="some-id"> <div class="dropdown">some elements& ...

Add jQuery and underscore libraries to an AngularJS component

For my new service, I am incorporating angularjs, underscore, and jQuery: myModule.factory('MyService', ['MyResource', function (MyResource) { .... // Utilizing _ and $ }]); How can I properly inject underscore and jQuery int ...

Unusual occurrences of backslashes in arrays when using JSON.stringify

While experimenting with JavaScript, I observed an unusual behavior when inserting a backslash \ into a string within an array and using JSON.stringify() to print it. Normally, the backslash is used for escaping special characters, but what if we actu ...

Preventing the default behavior using event.preventDefault() does not seem to be effective when submitting a

Why is the event.preventDefault() method not functioning properly? <script type="text/javascript" src="vue.js"></script> <div id="app"> <form v-on:submit.prevent="saveData"> <input type="text" name="test"> <button ...

Aligning container divs at the center in various screen resolutions

I recently constructed a portfolio website using Bootstrap and Isotope JS. In my layout, I have a container div which works perfectly when viewed on a desktop browser - displaying 3 divs in one line. However, the issue arises when the resolution changes an ...

JavaScript in fullscreen mode for Internet Explorer

I'm trying to make sure that this code snippet... $('#gatewayDimmer').width($('html').width()); $('#gatewayDimmer').height($('html').height()); $('#gatewayDimmer').css('display','block& ...

Discover the secret to smoothly scrolling to an element in ReactJs

Currently, I am in the process of constructing a Single Page Application (SPA) using React and one key functionality I need to implement is navigation that scrolls to specific sections on the page when clicked. This behavior is similar to how anchor tags w ...

Using setTimeout or setInterval for polling in JavaScript can cause the browser to freeze due to its asynchronous

In order to receive newly created data records, I have developed a polling script. My goal is to schedule the call to happen every N seconds. I experimented with both setTimeout() and setInterval() functions to run the polling task asynchronously. However ...

Issue with parentNode.replaceChild not functioning properly in Internet Explorer 6

In my HTML file created with FCK editor, I attempted to replace an existing table element with a new one using the parentNode.replaceChild method. While this change was successful in Internet Explorer 8, it resulted in errors when viewed in IE6 and IE7. ...