How to dynamically style NavLink using a variable in react-router-dom with Emotion?

Is there a way to extract styles to a variable when using react-router-dom's NavLink activeStyle prop? I want to avoid repeating the same styles without using a css file.

Ideally, I would prefer to achieve this using Emotion, but if that's not feasible, a regular variable would suffice.

Below is a sample of my code:

import { NavLink, useRouteMatch } from 'react-router-dom';
import { css } from '@emotion/react';

const navLinkStyle = css({
   color: blue,
});

const navLinkActiveStyle = { 
  color: 'red',
};

Here is the element in question:

   <NavLink
      to='/home'
      // activeClassName='selected' // I imagine this is for pure css styling, not css-in-js.
      css={navLinkStyle} // Emotion css prop
      activeStyle={navLinkActiveStyle} 
    >
      Home
   </NavLink>

Answer №1

You have the ability to consolidate all styling into a single object.

const buttonStyle = {
        color: 'red',
        fontSize: '16px',
        ...etc
    };

This object can then be applied in the following manner

 <Button
  onClick={handleClick}
  style={buttonStyle} 
>
  Click Me
</Button>

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

Automatic Clicks in the Chrome Console

I've come across a website that requires me to click on multiple elements scattered throughout the page Here is the code for one of the elements: <span class="icon icon-arrow-2"></span> Is there a way to provide me with the console comm ...

How do I properly configure my initial Next.js application?

I've been attempting to build a Next.js app. The command I typically use, npx create-next-app, used to work, but now it throws an error: Note: node -v 14.18.0 Using yarn. Installing dependencies: - react - react-dom - next 'yarn' is not r ...

Using HTML and CSS to Trigger Animation of Gif (or video) Upon Mouse Hover, Depending on Mouse Position

Is there a way to create an animation for a gif or video that changes based on the position of the mouse relative to the frame? For example, if the gif shows someone turning around 360 degrees, I would like the person to be facing forward when the mouse i ...

Having trouble dismissing Bootstrap alerts in TypeScript?

There seems to be an issue with the close button in a simple piece of code. The alert is displayed correctly, but clicking on the close button doesn't close the alert. Currently, I am using bootstrap 5.2.3. My code consists of a basic main file and an ...

Image floating to the left and right sides within a group, with the text vertically aligned in the middle of a div of unspecified height

Can text be vertically aligned in the middle of a div with an unknown height when there is a floated image present? Specifically, for the first and third div group of 'groupsection2', the image will float to the left; and for the second and fourt ...

Exploring nested routes with HashRouter in React

I've been working on a dashboard/admin control panel application using React, but I'm facing some challenges when it comes to handling component rendering accurately. Initially, my main App component is structured like this: <React.Fragment&g ...

CSS - Creating a stylish break line for link boxes

Struggling with creating a box that includes linked text and a line break. However, the issue arises when the line breaks, causing the box to also break. After trying multiple options, I still can't seem to find a solution. Check out my attempt her ...

Calculate the difference and sum of time values with varying signs in JavaScript

-12:00 - 5:30 => -6:30 -2:00 - 5:30 => 3:30 00:00 - 5:30 => -5:30 6:00 - 2:30 => 3:30 I am interested in subtracting time with both positive and negative indices. let myCountries = [ { countryName: "NewZealand", ...

Utilizing React with Typescript: A guide to working with Context

I have a super easy app snippet like import React, { createContext } from 'react'; import { render } from 'react-dom'; import './style.css'; interface IAppContext { name: string; age: number; country: string; } const A ...

Is opting to exclude the language file from the main bundle a viable strategy for minimizing the overall bundle size?

As I brainstorm ways to optimize my app's bundle size, I had a thought and would appreciate some feedback. Do you think it's advisable to exclude the language file altogether from the main bundle of an application? If your app is large with nume ...

Building a card carousel component in Vue JS

Struggling with creating a unique card slider using Vue JS? After exploring npm packages like Vue Carousel 3D and Vue Slick, I haven't found the ideal slider for my project. My specific card slider setup is showcased below: https://i.sstatic.net/GiNc ...

Advantages of using index.js within a component directory

It seems to be a common practice to have an index file in the component/container/module folders of react or angular2 projects. Examples of this can be seen in: angular2-webpack-starter react-boilerplate What advantages does this bring? When is it recom ...

What is the best way to efficiently handle onChange events for multiple input checkboxes in Reactjs?

When I attempt to assign an onChange event listener to a group of checkboxes, clicking on one checkbox results in all checkboxes being clicked and the conditional inline styles that I defined are applied to all of them. Here is the JSX code snippet: class ...

Opera's extra space feature allows users to comfortably browse the

I'm attempting to insert a progress bar inside a td element within my table. Below is the code: <td style="width: 150px;"> <div style="height: 16px; max-height: 16px; overflow: hidden; border: 1px solid #80C622;"> < ...

Enhance a path SVG component with properties for a map in a React application

My goal is to develop a strategy game using an SVG map that I have created. I want to include attributes such as "troops" in each "path" representing territories, along with other properties. Can I add these attributes to individual paths and then use this ...

Is there a way to eliminate black borders from a pop-up window?

When working with material UI, I noticed that the default import of a component includes black borders. Is there a way to modify the code so the box is completely white without any black borders? Looking for a snippet that can help me achieve this. Curren ...

Creating an opaque effect on a Material UI Drop down menu: Step-by-step guide

For the last half hour, I've been experimenting with my Select dropdown menu in an attempt to make it semi-transparent, but without success. I've tried adjusting the properties of the Paper, then the Menu, and then the MenuList, yet it appears th ...

Hovering over rounded corners is being blocked by transparent areas

I have a setup that resembles the following: http://jsfiddle.net/NhAuJ/ The issue arises when hovering near the edges of the circle because the square div blocks interaction with the background. I want to ensure that the circular div in the middle remain ...

How can I maintain consistent spacing between two areas in CSS3 across all screen sizes?

My question pertains to the alignment of an advertisement (on the left as a banner) and content sections on my website. I have noticed that as the screen size increases, the distance between these two areas also increases. How can I ensure that the distanc ...

Trouble with displaying Firestore data in React using useEffect hook upon initial page load

I have been working on displaying data from a firestore database by pushing it to an array and mapping it. The issue I'm facing is that the data only shows up after I make changes to my code, rather than on the initial page load. I suspect that the pr ...