Styling based on conditions, hovering effects, and implementing ReactJS

One issue I am facing is with an anchor element within a <div>. The anchor has conditional background styling, which seems to override the a:hover style. Whether I have conditional or fixed coloring, removing the background-style from component.js allows the hover effect from style.css to work correctly.

My main question is how can I maintain the hover effect while also using conditional background-coloring?

Snippet from component.js:

<div>
  <a href="#"
     style={{
       background: (day === 2) && "#f1f1f1"
     }} />
</div>

Snippet from style.css:

div a {
  display: block;
}
div a:hover {
  background: blue;
}

Answer №1

This showcases the comparison between CSS stylesheet and inline styles, where the former takes precedence due to css specificity.

Add a class to it and implement something like this.

.conditional {
  background-color: #f1f1f1;
}

.conditional:hover {
  background-color: red;
} 

Answer №2

Adding on, consider checking out styled components at . It's all about personal preference, but working with the style object can sometimes feel restricting and hard to follow (in my opinion). Some may find styled components challenging to understand - it's up to you. There's a lot more to discover about styled components, so it's definitely worth exploring further. In your scenario, you might use something like the example below (or have your styled component in a separate module)

import React from 'react'
import styled from 'styled-components'

const Link = styled.a`
  display: block;

  & :hover {
    background: ${props => props.dayValue === 2 ? white : blue};
  }
`

render(){
  return (<div> <Link href='' dayValue={this.props.dayValue}/></div>)
}

Answer №3

To ensure that the hover behavior is maintained even when inline styles are present, you can utilize the !important declaration, like this:

div a:hover {
  background: blue !important;
}

If you do not require dynamic inline styling, it is advisable to steer clear of using !important and opt for class based styling instead:

JSX

<div>
  <a href="#" className={ (day === 2) && "dayTwoClass" } />
</div>

CSS

div a {
  display: block;
}

// Higher specificity of div to a results in blue background on hover
div a:hover {
  background: blue;
}

// Lower specificity leads to #f1f1f1 background when not hovered
.dayTwoClass {
  background: #f1f1f1;
}

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

Having trouble with Python Selenium CSS Selector? If your element is not visible, it

My goal is to search for all hyperlinks on a webpage that contain an XML download link and download them in a continuous loop. When I click on these hyperlinks, a form pops up that needs to be completed before I can proceed with the download. However, I ...

Having trouble with applying a class in Gtk3 css?

MY ATTEMPT AND EXPLANATION: In my application, I have the following layout structure: GtkWindow GtkOverlay GtkBox GtkGrid GtkButton Even after trying to apply this CSS style: GtkButton{ background-color:blue; } T ...

What is the best way to delay JavaScript execution until after React has finished rendering?

Perhaps this is not the exact question you were expecting, but it did catch your attention :) The issue at hand revolves around the fact that most of the translations in my text do not update when the global language changes. Specifically, the translation ...

Having trouble getting a resizable DIV inside a 100% height DIV with margin to work properly. Any tips or assistance would be greatly

I've encountered a common issue that is slightly different from others I've come across. Despite my best efforts, I have been unable to find a solution on my own. If anyone could offer me some guidance on this, I would greatly appreciate it. The ...

I'm having trouble locating the documentation for jssPreset in this CodeSandbox. It seems to be missing

import { jssPreset, StylesProvider, makeStyles } from '@material-ui/core/styles'; Can anyone help me locate the documentation for jssPreset in this CodeSandbox? I'm unsure about its meaning and would like to refer to the documentation, but ...

Ways to make video controls visible following the initial click on the video

I have a collection of videos on my website and I would like them to display with a poster (thumbnail image) initially. The video controls should only appear once the user clicks on the video for the first time. Therefore, when the page is loaded, the cont ...

Error encountered while rendering with ReactDOM and webpack

I encountered this perplexing error that I cannot seem to figure out, The line where I was rendering MuiThemeProvider in the react dom looks like this: ReactDOM.render( <MuiThemeProvider muiTheme={getMuiTheme()}> <Router history={browserHi ...

Error message received: `TypeError: _this.props.setCurrentUserHandle is not defined in mapDispatchToProps for Redux`

I'm encountering a strange error while trying to make a simple react-redux app work. Specifically, I am struggling with setting my current user's first name and handle in the store using two set functions - one works, but the other doesn't. ...

Having trouble accurately referencing the domain across various servers

I have set up two servers for production - one for php files and the other for static (css, js) files. Within my config.php file: $path ="https://mystaticdomain.com/"; To simplify access to paths, I created a variable to store the path for css and js fi ...

The web browser's engine is blocking the connection to the secure websocket server

Summary of Issue An error message stating "Websocket connection failed." appears in the browser console (Chrome or Brave) when trying to run this code: const ws = new WebSocket("wss://abcd.ngrok-free.app/") (Please note that the URL mentioned is not real ...

The text in the <p> tag will remain the same color

I am encountering an issue with changing the color in the <p> tags within the code snippet below. Specifically, I am trying to change the TITLE text to gray but have been unsuccessful so far. If anyone could provide assistance on this matter, it wou ...

Storing array values in a MySQL database within the Laravel framework

I am currently working on developing a REST API in Laravel. I am facing an issue where I need to post array data into the database, but I am unsure of how to do it. Can anyone provide guidance on this? I am new to Laravel. ProductdetaisController.php < ...

Leveraging CSS or JavaScript for Displaying or Concealing Vacant Content Sections

I'm working on developing a page template that utilizes section headers and dynamically pulled content from a separate database. The current setup of the page resembles the following structure: <tr> <td> <h3> ...

Issue: In Firefox, resizing elements using position:absolute does not work as expected

My resizable div code looks like this: #box { height: 10rem; width: 10rem; resize: both; overflow: hidden; border: solid black 0.5rem; position: absolute; pointer-events: none; } <div id="item"></div> While it works perfectly ...

Adjust the position of a textarea on an image using a slider

Currently, I am exploring how to creatively position a textarea on an image. The idea is to overlay the text on the image within the textarea and then use a slider to adjust the vertical position of the text as a percentage of the image height. For instanc ...

Row within a table displaying link-like behavior

Here is the code I'm currently using: $('.table-striped tr').click( function() { var link = $(this).find('a').attr('href'); if(link != 'undefined') { window.location = link; } }).hover( func ...

Combine a variable and a string to create a new variable

@color-purple: "#ffffff" @colors: purple, light-purple, green, light-green, red, light-red, grey, light-grey, lightest-grey; .ColorsMixin(@i:0) when(@i =< length(@colors)){ //loop over icons array @color: extract(@colors, @i); //extract the ic ...

Exploring ways to incorporate the context value into my component's functionality

Hi, I'm new to TypeScript and I'm facing an issue when trying to use a value I created in my context API. I keep getting the error message "Property 'sidebar' does not exist on type 'IStateContext | null'", even though it exis ...

The removal of classList.remove() only eliminates the class itself, not its contents

My goal is to add one class and remove another class when the start quiz button is clicked. While the 'info_box' class is successfully added, the 'start_btn' class does not get removed; it just changes position (from flex to no flex). T ...

The HTML modal closing button is unresponsive and the contents inside are misaligned, causing functionality issues

I've searched through similar questions, but none of the suggested solutions seem to work for my issue. The problem I'm facing is that the closing button on my modal isn't functioning properly and the content inside it is not aligning corre ...