Alter the appearance of a functional component upon clicking

The AnswerScreen component is currently loading a set of MyButton components. I am trying to adjust the style of the MyButton that was clicked, specifically changing the backgroundColor. Unfortunately, my code is not functioning as expected. I have noticed that in a class component, I could achieve this with this.className, but in a functional component, it seems like I cannot utilize this approach (despite having the key). Any suggestions or tips on how I can accomplish this?

import React from 'react';
import classes from './AnswerScreen.module.css';
import MyButton from '../../../../utils/MyButton';
    
const AnswerScreen = (props) => {
        
    const buttonClickHandler = (index, value) => {

        if (props.myValue !== value) {
            classes.AnswerScreenButton = {
                fontSize: '3rem',
                cursor: 'pointer',
                backgroundColor: 'red'
            }
        }
    }

    return (
        <div className={classes.AnswerScreen}>
            {props.buttons.map((value, index) => {
                 return <MyButton 
                    className={classes.AnswerScreenButton} 
                    clickHandler={() => buttonClickHandler(index, value)}
                    key={index} 
                    num = {value} />
            })}
        </div>
    );
}
    
export default AnswerScreen;

Answer №1

If you're looking to keep track of the selected button, I recommend adding a state variable for that purpose. Use the state variable to manage the button's classname accordingly. Consider creating a class called AnswerScreenButtonSelected with CSS styles for highlighting the selected button. Avoid using index when setting keys in mapped arrays within React components.

import React from 'react';
import classes from './AnswerScreen.module.css';
import MyButton from '../../../../utils/MyButton';

const AnswerScreen = (props) => {
  const [selectedButton, setSelectedButton] = useState(null);

  return (
      <div className={classes.AnswerScreen}>
           {props.buttons.map(value =>
               <MyButton 
                  key={value} 
                  className={selectedButton === value ? classes.AnswerScreenButtonSelected : classes.AnswerScreenButton} 
                  clickHandler={() => setSelectedButton(value)}
                  num={value} />
          )}
      </div>
  );
}

export default AnswerScreen;

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

The design of the page is structured around Semantic-UI Grid, and unfortunately, the spacing between elements cannot

Currently, I'm in the process of developing a web application with the help of semantic-ui. The primary objective is to design a layout that comprises a sidebar along with a main content area. Initially, I assumed that utilizing grid would be the most ...

The lifecycle of a Field component in React JS with Formik does not inherit the same props as its parent Formik component

I am working on a parent component that uses Formik Parent Component: <Formik validationSchema={validationSchema} render={({ props }) => ( //… more code <ChildrenComponent props={props} /> )} /> Child ...

Error Panel Style Message Format:

Currently, I am utilizing PrimeFaces, which utilizes JQuery UI not just for its functionality but also for its CSS styling framework. The issue I am facing stems from my lack of understanding about the CSS framework, as I have been unable to locate any exa ...

Tips for implementing hover style on a disabled element within the TextField component in mui version 5

I want to change the color of a disabled element within the TextField component when it is hovered over. To see an example, check out this demo import * as React from "react"; import TextField from "@mui/material/TextField"; import { ...

Difficulty encountered when trying to map an array to JSX - Error: Unexpected token

I am struggling to properly map an employees array to a new array using ReactJS and JSX. It seems like there is an issue with my return method. Please keep in mind that I am a complete beginner when it comes to React and ES6. Can someone guide me on how t ...

Changing the caret position in a contenteditable div using HTML React

In a recent project I worked on, I included contenteditable divs. Whenever the enter key is pressed within one of these divs, it splits into two separate contenteditable divs. However, after React re-renders the components, the caret tends to go to the beg ...

What is the process for updating the background color of the header in ngx datatable?

I am looking to change the background color of the table header to blue. This is the HTML code I have: <ngx-datatable class="material" [rows]="rows" [columnMode]="'force'" [headerHeight]="50" [footerHe ...

Extract the Floating Number and Set as Fixed Decimal with Zero Decimal Places

I have a react-native code snippet that I'd like to modify. <Grid item xs={12} sm={12} md={12} lg={12} style={{textAlign:isRTL==='rtl'?'right':'left'}}> <Typography color={'primary'} style={{fo ...

Implementing dynamic rendering of elements in Next.js using data from FaunaDB

I am currently working on a feature that displays different elements based on the users' job profile status. To fetch the necessary data, I'm utilizing FaunaDB along with useSWR. When I console.log(userData), I receive the following object: jobPr ...

The background color of the body is being utilized by Div in Internet Explorer version 7

Within my HTML document, I have created a container div that holds several nested divs for a slideshow effect. This "container" div is positioned over the background image of the body element. The CSS styling for the body element is as follows: body { ba ...

Using setState in conjunction with dispatch from Redux will cause the entire component to re-render and reset the updated state

I am working on a component called CheckboxColumn const CheckboxColumn: FC<ICheckboxColumnProps> = ({ id_llamada }) => { // implement functionality for selecting pickup const dispatch = useTypedDispatch(); const [isPickupSelected, se ...

Activate the overflow feature within native-base cards

I have a unique design element on a website that showcases an image overflowing off a card. The image has a negative margin-top of -50, creating this effect. Now I'm trying to replicate this design in react-native using native-base components. Here i ...

Error: An invalid object was passed instead of a stream in Redux-observal. Fix this issue

An error has occurred: TypeError - You have provided an invalid object when a stream was expected. The acceptable types are Observable, Promise, Array, or Iterable. //action.js import { map,mergeMap } from 'rxjs/operators'; import {ofType } from ...

Arranging elements in HTML for Manipulating with JavaScript

I haven't started coding yet, but I'm contemplating the overall strategy. My front end is primarily composed of HTML tables, giving it an Excel-like appearance. I am considering generating default pages and then using JavaScript to dynamically m ...

Arranging divs in a horizontal line while keeping the content organized in a vertical manner within the footer

I've been searching for a while now, but I haven't found any solutions that actually work. This might be repetitive, so my apologies in advance. The issue at hand is aligning three divs horizontally to create a footer, while maintaining a vertic ...

The next-auth credential provider has the ability to sign me in and create a session, regardless of incorrect details or errors

I'm getting tired of dealing with this persistent error. Despite unsuccessful logins, the next-auth credential provider still manages to sign me in and create a session for me. session: {user: {…}, expires: '2023-04-26T03:59:46.157Z'} ex ...

Changing font color of a selected item in Material-UI's textview

I have a select textview in my react app and I am wondering how to change the font color after selecting an item from this textview. <div> <TextField id="standard-select-currency" select fullWidth l ...

Guide to Creating a Seamless Fade Effect for Hover Backgrounds

I have a collection on my site and the background of each <li> item is filled with a 1 pixel black color image at 30% opacity, repeating to cover the entire <li>. Upon hovering, it changes to a 1 pixel white color image at 2% opacity. Instead ...

Transferring parameters from HTML to CSS using Less and addressing two key design problems

I am currently in the process of designing a webpage, and I've encountered three distinct issues - two are related to pure .css, while one is related to less. Firstly, I have set margin: auto and padding: auto on the body tag, but it's not cente ...

Enable clickable elements positioned behind an iframe

I am currently working on integrating a third-party chatbot into my web application using an iframe in ASP.NET MVC. Like with any chatbot, a button is provided to start a chat (located on the right-hand side below the screen). When this button is clicked, ...