Updating Icon on Button Click with React.js

Looking for help with a React function that generates buttons.

<div className="col-6 btn-group btn-group w-100">
       <AuditMenuButtons buttonValue='Pending' buttonName='Inbox' changeFilterForButton={this.props.changeFilterForButton} icon={icon_inbox}/>
       <AuditMenuButtons buttonValue='Rejected' buttonName='Rejected' changeFilterForButton={this.props.changeFilterForButton} icon={icon_rejected}/>
       <AuditMenuButtons buttonValue='Accepted' buttonName='Accepted' changeFilterForButton={this.props.changeFilterForButton} icon={icon_accepted}/>
</div>

Below is the accompanying function:

    function AuditMenuButtons(props) {
    return(
        <button className="w-25 btn menu-btn p-lg-3" name={props.buttonName} value={props.buttonValue} onClick={props.changeFilterForButton}><img src={props.icon} className="pr-3 menu-btn-icons">
        </img>{props.buttonName}</button>
    );
}

The code above displays 3 buttons. The objective is to change the color of the button icon to green when clicked, and maintain this color until another button is clicked or the page is refreshed. The images used are .png files with green and silver borders. Attempts using CSS pseudo-class :active were unsuccessful. The goal is to persist the green color on the clicked button's icon.

Answer №1

Within this scenario, the icon element serves as a representation of a UI state, which needs to be managed within your application's state and then transmitted to the AuditMenuButtons component as props.

Utilize these props within the AuditMenuButtons component to perform the necessary validation checks.

        import React,{Component} from 'react';

        class customComponent extends from Component{
            this.state={
               isClicked:false,
               buttonIcons:{
                  pending:{active_Icon:"../IconURL",Icon:"../IconURL"},
                  rejected:{active_Icon:"../IconURL",Icon:"../IconURL"},
                  accepted:{active_Icon:"../IconURL",Icon:"../IconURL"}
               }
            }

           clickHandler = (event) =>{
             this.setState(
              {
                isClicked:!this.state.isClicked // Toggles each time it is clicked //
              }
             );
           }

           render(){
              return <div className="col-6 btn-group btn-group w-100">
                     <AuditMenuButtons clickhandler={this.clickHandler} buttonValue='Pending' buttonName='Inbox' isClicked={this.state.isClicked} buttonIcons={this.state.buttonIcons} changeFilterForButton={this.props.changeFilterForButton} icon={icon_inbox}/>
                     <AuditMenuButtons clickhandler={this.clickHandler} buttonValue='Rejected' buttonName='Rejected' isClicked={this.state.isClicked}  buttonIcons={this.state.buttonIcons} changeFilterForButton={this.props.changeFilterForButton} icon={icon_rejected}/>
                     <AuditMenuButtons clickhandler={this.clickHandler} buttonValue='Accepted' buttonName='Accepted'  isClicked={this.state.isClicked} buttonIcons={this.state.buttonIcons} changeFilterForButton={this.props.changeFilterForButton} icon={icon_accepted}/>
              </div>
           }
        }

        export default customComponent;

Answer №2

If you want to change the style of a button when it is focused, consider adding the following code snippet to your .css file.

.button:focus{background-image: url('your custom green image');

Answer №3

To dynamically update the image path in React, you can store the path in the component's state and then call a method to change it on onClick event by using setState().

For more information, check out: https://reactjs.org/docs/handling-events.html

Learn about setState() here: https://reactjs.org/docs/react-component.html#setstate

this.state = {
  image_path: 'your image url here'
}

changePath = () => {
  this.setState({image_path:'new path'});
}
<AuditMenuButtons onClick={this.changePath} src={this.state.image_path}/>

Answer №4

Here is a suggestion you can try:

updateFilterForButton: function (props) {
     props.currentTarget.style.backgroundColor = '#ccc';
}

function CustomizeMenuButtons(props) {
    return(
        <button className="w-25 btn menu-btn p-lg-3" name={this.props.buttonName} 
value={this.props.buttonValue} onClick={this.props.updateFilterForButton}><img src={this.props.icon} className="pr-3 menu-btn-icons">
        </img>{this.props.buttonName}</button>
    );
}

If you prefer to use React methodology, you can utilize the constructor like this:

constructor(props) {
    super(props);
    this.state = {isColor: false};

    // This binding is necessary to make `this` work in the callback
    this.updateFilterForButton= this.updateFilterForButton.bind(this);
  }

  updateFilterForButton() {
    this.setState(state => ({
      isColor: !state.isColor
    }));
  }


  function CustomizeMenuButtons(props) {
    return (
<button className="w-25 btn menu-btn p-lg-3" name={props.buttonName} value={props.buttonValue} onClick={props.updateFilterForButton} style="background-color: {this.state.isColor? '#CCC' : ''} "><img src={props.icon} className="pr-3 menu-btn-icons">
    </img>{props.buttonName}</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

Is it possible to modify the hue of the circular progress circle on this MUI component?

Is it possible to customize the color of the circle on this MUI circular progress? I found this code on the official MUI page, https://mui.com/components/progress/ (Circular with label), where there is a CodeSandBox for experimenting with properties. (I c ...

Is it possible to apply paper elevation through css properties?

With my material UI app, I've focused on keeping all styling in CSS using makeStyles, rather than mixing JSX styling with CSS as suggested by the material UI docs. So far, this approach has worked well for me, but I'm facing an issue with applyin ...

Is it possible for a div nested within another div to still occupy space on the page despite being set

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $("select#choosebook").change(function(){ $(".title").slideDown(" ...

Using React Inline Styles to Set a Background Image

I am facing an issue with accessing a static image to use as a background within the backgroundImage property in React. I have hit a roadblock and need some guidance on how to proceed. My initial thought was that it could be achieved by following these st ...

Using Google Fonts with AMP and Ruby on Rails: A Challenging Task

I am currently in the process of implementing AMP pages on my Rails application. Unfortunately, I am facing difficulties with getting my font to display correctly. The Google Search Console is returning the following error message: "CSS syntax error in th ...

How can you tell if a contenteditable div is currently in focus?

Essentially, my setup consists of: HTML: <div class="div1"> <div class="as-text-box" contenteditable="true"></div> </div> CSS: .div1{ position:absolute; height:50px; width:200px; background:white; border:1px solid #c ...

Adding a class to an img tag with TinyMCE

Currently, I am utilizing the TinyMCE editor as a standalone editor in my content management system (CMS). Within the CMS, there is an automatic setting that adds a curved border to any image tags within the cms div ID. In certain cases, I require the op ...

Alignment of input fields and labels in Bootstrap by utilizing the Grid System

Currently, I am in the process of developing a form that includes multiple input fields. To organize these fields, I have utilized the Bootstrap 4 Grid system. However, I am encountering challenges when it comes to aligning certain input fields. Snippet ...

Unused React import in the index.js file

Just starting to explore the world of reactJS. import React from 'react'; import ReactDOM from 'react-dom'; var App = ()=>{ return <div> Hello !!</div> } ReactDOM.render(<App />, document.getElementById(' ...

Is it possible to develop a chat application utilizing only react, node js, and mongoose? Would socket.io be necessary for this project?

As I work on developing a straightforward chat application using react and node js, the use of sockets for establishing server-client connections raises questions for me. Given that react automatically re-renders the page upon state changes, it seems fea ...

Error: CSS and JavaScript files cannot be found

Currently working with an Orchard Asp.net MVC 3 Project. Upon examining the source code in the browser, I notice all the JS and CSS files being referenced/imported. However, clicking on the URL for certain JS files located in the MediaLibrary or Modules f ...

Make sure the div can grow in height as needed, but if it reaches the limit of its container, it

UPDATE: I've created a JSFiddle for testing purposes. Below is an example of what I aspire to achieve (with Bootstrap 4 rows and columns): https://i.sstatic.net/hfXno.png The page should only display scrollbars if the second row is fully compress ...

HTML5 text can display letters and numbers at varying heights

Can anyone explain why the numbers and letters are displaying at different heights? I am utilizing Bootstrap 3. HTML <ul class="list-group"> <li class="list-group-item">HTML5</li> <li class="list-group-item"&g ...

Utilizing parameters and variables as function arguments in reactjs

I have created a function type React component: function Card(props, {icon}) { return ( <div className="card"> <FontAwesomeIcon icon={icon} className="icon"/> <h3 className="text">{props.name}</h3&g ...

JavaScript and React.js encounter glitch in AWS Cognito authentication function

I'm currently troubleshooting a issue in my code where there is no validation to prevent a user from signing up with the same email twice: Below is my onSubmit code: async function handleSubmit(event) { event.preventDefault(); setIsLoading( ...

What is the best way to achieve text elements overlapping each other in CSS?

Imagine having the following HTML: <div> hello <div>hello</div> </div> Wouldn't it be cool if those two texts overlapped perfectly in the center? It doesn't matter which one overlaps the other. Do you think it' ...

Error: Package.js detected multiple versions of fbjs installed

While attempting to update from version 0.10.5 to 0.11.0, I encountered the following error message. Surprisingly, gbjs is not even included in my package.js file. [compileVendorDll] ERROR in fbjs [compileVendorDll] Multiple versions of fbjs found: [com ...

Can Antd's Typography.Paragraph be used as a multi-row Menu title?

I am having trouble getting multiple rows to work inside the Antd Submenu. When I select only one row, it works fine. However, when I try to select multiple rows, the ellipsis is not shown at all and the text remains in one row. <SubMenu ...

The command to fix Eslint is not able to resolve all of the errors related to vue/html-indent

In my .eslintrc.js file, I have set up some linting rules as shown below: module.exports = { root: true, env: { browser: true, es6: true, node: true, }, extends: ['plugin:vue/recommended', 'eslint:recommended'], pa ...

What is the most effective way to organize a large number of icons in React?

Having multiple Icon components structured as follows: import { IconProps } from "@utils/types"; const FilterIcon = (props: IconProps) => { const { fillColor, width, height } = props; return ( <svg width={width} height ...