What causes certain components in ReactJs to not respond to the `:focus` pseudo-class?

Currently, I am in the process of implementing a straightforward Emoji-Rating system where 5 emojis are displayed on the screen and upon hovering over them, their appearance changes. This functionality is achieved using the :hover pseudo-class. My goal is to make it so that when a user clicks on one of the emojis, it remains in its hovered state even after the cursor moves away. However, whenever I click on an emoji and move the cursor off, it reverts back to its original look.

Below is the ReactJs form code:

<form className='ratingForm' onSubmit={(event) => handleSubmit(event)}>
            <div className='inputs'>
              <div className='inputWrapper'>
                <div id="angry-emoji-wrapper" className='emoji-wrapper angry'>
                  <EmojiAngry passedProp={getChildProps} value={0} />
                </div>
                <label className='inpLabel' htmlFor="0">Very Bad</label>
              </div>
              <div className='inputWrapper'>
                <div id="frown-emoji-wrapper" className='emoji-wrapper frown'>
                  <EmojiFrown passedProp={getChildProps} value={1} />
                </div>
                <label className='inpLabel' htmlFor="1">Bad</label>
              </div>
              <div className='inputWrapper'>
                <div id='neutral-emoji-wrapper' className='emoji-wrapper neutral'>
                  <EmojiNeutral passedProp={getChildProps} value={2} />
                </div>
                <label className='inpLabel' htmlFor="2">Average</label>
              </div>
              <div className='inputWrapper'>
                <div id='smile-emoji-wrapper' className='emoji-wrapper smile'>
                  <EmojiSmile passedProp={getChildProps} value={3} />
                </div>
                <label className='inpLabel' htmlFor="3">Good</label>
              </div>
              <div className='inputWrapper'>
                <div id='laughing-emoji-wrapper' className='emoji-wrapper laugh'>
                  <EmojiLaughing passedProp={getChildProps} value={4} />
                </div>
                <label className='inpLabel' htmlFor="4">Very Good</label>
              </div>
            </div>
            <button className='btn btn-success' type="submit">Submit</button>
          </form>

One of the Emoji components utilizing the react-icons npm package:

import { BsEmojiAngryFill } from 'react-icons/bs';

export default function EmojiAngry(props) {

    function handleClick() {
        props.passedProp(props.value);
    }

    return (
        <BsEmojiAngryFill onClick={handleClick} />
    )
}

Here is the CSS associated with the emojis:

/*==================================EMOJI===================================*/
svg {
  width: 70px;
  height: 50px;
  color: rgb(201, 201, 201);
}

/*ANGRY*/
#angry-emoji-wrapper.emoji-wrapper.angry:hover>svg,
#angry-emoji-wrapper.emoji-wrapper.angry:focus>svg {
  color: #de332b !important;
  transform: scale(1.2) !important;
  transition: all .1s ease-in-out !important;
  cursor: pointer !important;
}

I have attempted to utilize tabIndex={0}, but this only resulted in an outline that fluctuated in size based on the current scale of the emoji. I also experimented with various CSS approaches, such as not just separating hover and focus states with commas. Furthermore, I explored employing the :active pseudo-class, but unfortunately, to no avail.

Answer №1

After some experimentation, I successfully resolved the issue by introducing a new class that changes based on whether the emoji is clicked. This class is then incorporated within the CSS.

Here is a snippet of the solution:

const [selectedEmoji, setSelectedEmoji] = useState(null);

function getChildProps(value) {
setRating(value);
setSelectedEmoji(value);
console.log(value)
}

<div className={`inputWrapper`}>
            <div id="angry-emoji-wrapper" className={`emoji-wrapper angry ${selectedEmoji === 0 ? 'selected' : ''}`}>
              <EmojiAngry passedProp={getChildProps} value={0} />
            </div>
            <label className='inpLabel' htmlFor="0">Very Bad</label>
          </div>

No modifications were made to the component itself. The accompanying CSS looks like this:

/*==================================EMOJI===================================*/
svg {
  width: 70px;
  height: 50px;
  color: rgb(201, 201, 201);
}

/*ANGRY*/
#angry-emoji-wrapper.emoji-wrapper.angry:hover>svg,
#angry-emoji-wrapper.emoji-wrapper.angry:focus>svg,
#angry-emoji-wrapper.emoji-wrapper.angry.selected>svg {
  color: #de332b !important;
  transform: scale(1.2) !important;
  transition: all .1s ease-in-out !important;
  cursor: pointer !important;
}

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

Select a color by inputting the type as "color" while leaving a space between the border and

I'm having an issue with the color input There seems to be a gap between the black border and the actual color, but I want to get rid of it #color-picker { border: 5px solid black; border-radius: 5px; width: 207px; height: 60px; padding: ...

Using React.js to create table cells with varying background colors

For my React application, I am working with a table that utilizes semantic ui. My goal is to modify the bgcolor based on a condition. In most cases, examples demonstrate something like bgcolor={(condition)?'red':'blue'}. However, I requ ...

Issues with jQuery animate not functioning properly when triggered on scroll position

I found a solution on Stack Overflow at this link, but I'm having trouble implementing it properly. The idea is to make an element change opacity from 0 to 1 when the page is scrolled to it, but it's not working as expected. The element is locat ...

What is the quickest method for upgrading node and npm?

Despite my numerous online searches, I am still unable to get it to work. Can someone clarify if my understanding is correct? To upgrade npm to the latest version: npm install npm@latest -g To update node to the latest version: Visit the official webs ...

The useParams() function will return an empty value upon the component's initial render

I'm utilizing React along with the following libraries: "babel-eslint": "10.0.3", "react": "^17.0.2", "react-dom": "^17.0.2", "react-redux": "^7.2.4", "react-router-dom": "^6.3.0", "react-scripts": "3.2.0", "redux": "^4.1.1 ...

ESLint is not performing linting even though the server is operational

I found a frontend template online and successfully installed all the packages using yarn. However, although I have an .eslint.json file in place and the ESLint extension is installed in Visual Studio Code, I am not seeing any linting errors. Below is the ...

enigmatic issue arising in Angular/Node

Could someone please shed some light on what might be causing the issue in my code? Thank you in advance! webpack: Compilation Failed. My Angular CLI: 1.6.3 Node: 8.9.4 OS: Windows 32-bit Angular: 5.2.1 Error Message: ERROR in ./node_modules/css-loader ...

You can only use a parameter initializer within the implementation of a function or constructor

I recently started learning TypeScript and am currently using it for React Bricks. I've been working on rendering a 3D object with three.js, but I keep encountering the error mentioned above. I've attempted various solutions such as passing color ...

The type '(props: Props) => Element' cannot be assigned to the type 'FunctionComponent<FieldRenderProps<any, HTMLElement>>' in React-final-form

I'm fairly new to using TypeScript, and I am currently working on developing a signUp form with the help of React-Final-Form along with TypeScript. Here is the code snippet that describes my form: import React from "react"; import Button from "@mater ...

Managing User Information in a Next.js Application using Clerk and MongoDB

Exploring the world of Next.js and diving deep into its application architecture has been an exciting journey. With Clerk and MongoDB in the mix, I find myself pondering some important questions: User Data Management: In my Next.js 14 project powered by ...

jQuery's AJAX feature fails to identify the newly modified div classes

For my new website, I am developing a simple checklist feature. To handle the check and uncheck requests from users, I'm using jQuery's $.ajax() function. Whenever a user clicks on the check or uncheck buttons, jQuery retrieves the validation tok ...

Tips for organizing a Material UI DataGrid table effectively while keeping the total sum rows within the DataGrid unaffected

Check out my codeSandbox link here: https://codesandbox.io/s/making-sum-of-column-in-datagrid-mui-zjzfq6?file=/demo.js I've noticed that when I sort by ascending, the subtotal, total, and tax rows move up, but when I sort by descending, they move dow ...

Tips for selecting the best className type for material-ui components

Currently, I am integrating material-ui into a react app that is built using typescript. Within the material-ui framework, there is a feature called withStyles which allows styles to be injected into a component through its className. However, I am facing ...

Using npm to add a SOAP client with authentication headers

I am currently working on integrating the npm soap package to establish endpoints for a remote server that can be accessed via Angular 4. Despite going through the documentation, I still find myself uncertain about its practical application. The WSDL provi ...

npm ERROR! The requested resource at http://registry.npmjs.org/amcharts4 could not be located - Error 404: Resource Not Found

I'm running into an issue while trying to include npm package dependencies in my Angular project. Can anyone assist me in resolving this error? C:\Users\TM161\Desktop\Master\stage PFE\SNRT-Music>npm i npm ERR! code ...

Trouble with webpage design persists following recent modifications

Today, I decided to make some alterations on the header.php file of my WordPress website in order to tweak the flag icons displayed at the top of the page. However, when I refreshed the page, everything looked completely chaotic. Even after undoing all th ...

When using React, the event.target method may unexpectedly return the innerText of a previously clicked element instead of the intended element that was

I have implemented a drop-down menu that triggers an event handler to return the selected option when it is clicked. Upon clicking on an option, I retrieve the inner text of that option using the event. The code snippet looks like this: event.target.inner ...

Struggling to synchronize animation timing between elements using jquery

When you navigate to an album (for example, Nature because I'm still working on the others) and select one of the images, they all gradually fade out while the selected image appears on the screen. What's actually happening is that the selected i ...

Send a property as a string, then transform the string back into JavaScript

I am in the process of creating a versatile carousel that will cater to various conditions. Therefore, I need to set the "imageQuery" on my display page as a string and then make it work as executable javascript within my carousel. The query functions pr ...

Locate the package.json file while executing an npm script during the preinstall phase

Before installing a new npm package, it is essential to read the package.json. The Importance of Reading package.json When using npm for CSS components with individual versioning and possible interdependencies (without JavaScript), conflicts may arise. D ...