Tips for updating button dimensions and colors on the fly in React

Currently, I have developed a custom Button component in my React application. At the moment, I am able to dynamically modify the color by specifying it within the color attribute. However, I now aim to provide an option to change the size of the button as well (e.g. 'small', 'large'). Since I am still relatively new to CSS, I am unsure about the best approach for achieving this.

This is my Button.css file:

.ButtonUI {
    border-radius: 4px;
    border: none;
    padding: 10px 24px;
    margin-right: 20px;
    margin-left: 20px;
}

.G-green {
    color: white;
    background-color: #0F9D58;
}

.small {
    border-radius: 4px;
    border: none;
    padding: 6px 12px;
}

.ButtonUI.G-green:hover{
    cursor: pointer;
    background-color: #0d8c4f;
}

(Green, Blue, Red, Yellow and Teal classes with respective hover states)

In my Button.js file:

import React from 'react'
import '../../StyleSheets/Button.css'

export default class Button extends React.Component{
    constructor(props){
        super(props);

        this.state = {

        }
    }

    render(){
        return(
            <div id="button">
                <button className={"ButtonUI " + this.props.color + this.props.size} onClick={this.props.click} id={this.props.name}>{this.props.name}</button>
            </div>
        )
    }
}

I attempted to use the component like this:

<Button color="G-green" size="small" name="Click Me"></Button>
, but this resulted in my css breaking and the button showing up blank.

If anyone has insights on the most effective approach to tackle this issue, I would sincerely appreciate your assistance. Thank you!

Answer №1

<button className={`ButtonUI ${this.props.color} ${this.props.size}`} onClick={this.props.click} id={this.props.name}>{this.props.name}</button>

Alternatively

<button className={['ButtonUI', this.props.color, this.props.size].join(' ')} onClick={this.props.click} id={this.props.name}>{this.props.name}</button>

Another option is to use the classnames package for conditional classes:

import classNames from 'classnames'

<button className={classNames('ButtonUI', this.props.color, this.props.size)} onClick={this.props.click} id={this.props.name}>{this.props.name}</button>

Answer №2

Hey there, I just developed this new code snippet for you:

function Component() {
         super();
         this.state = {
              darkMode: true
         }
    }
    
    toggleTheme() {
        this.setState({darkMode: !this.state.darkMode})
    }

    render(){
        let btnStyle = this.state.darkMode ? "darkButton" : "lightButton";

        return (
             <div>
                 <button className={btnStyle}
                         onClick={this.toggleTheme.bind(this)}>
                           Click Me
                  </button>
             </div>
        )
    }

Feel free to customize the CSS as needed:

button{
  width: 80px;
  height: 40px;
  margin: 15px;
}

.darkButton{
  background-color: black;
  color: white;
}

.lightButton{
  background-color: white;
  color: black;
  width: 120px;
  height: 140px;
  margin: 15px;
}

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 unique filter in Angular.js seems to be malfunctioning

I ran into an issue with my code where I expected my paragraphs to filter out values based on unique age, but instead I encountered the unknown provider error. How can I resolve this? <html> <head> <script src="https://cdnjs.cloudflare.com/ ...

Text in various styles is layered on top of an image, ensuring that text in one style does not overlap text in another style

Struggling with placing text over an image? Trying to achieve different text styles but ending up with overlapping lines? Here's a snippet of HTML that works with only one text style: <li style="" class="portfolio-content-CV"> <div class ...

Generate the entity and then transfer the data into an array

I am dealing with multi-level hierarchies that need to be displayed in a select list. Once the user selects values from the table column, they should be able to filter by clicking on the column. var name = ['Akansha', 'Navya']; var age ...

Is it possible to invoke the created() function in Vue from another method?

Currently, I am developing an application in Vue. Upon loading the page, a cookie containing the user's zip code is retrieved and used to perform a search. However, users should also have the ability to change their zip code if it is incorrect. I woul ...

What is the best way to conceal a parent element with jquery?

Let's say we have the following HTML structure: <li class="fooli"> <a class="foo" href="javascript:foo(this);">anchor</a> </li> <li class="fooli"> <a class="foo" href="javascript:foo(this);">anchor</a> ...

How can I dynamically change a key in an object and replace it with a custom name while also updating its value?

Transform this =>>>>> {1: "Baroque", 2: "Glitch Pop ", 3: "Nu Jazz", 4: "Drumfunk", 5: "Bitpop", 6: "Latin Pop", 7: "Carnatic"} into this ==>>>> [{id: 1 name ...

Tips for transferring information obtained from an API to my custom HTML page

As a novice in web development, I recently created a simple weather report website using the OpenWeather API. While I successfully fetched data from the API, I encountered an issue trying to display this data on my HTML page. Despite utilizing DOM manipu ...

Implementing Ideone API functionality on Codeigniter with the use of ajax, javascript, and soapclient

I am new to using Codeigniter and I apologize if my question is basic. I found some code on this site: Working with IDE One API (Full project code available here) and I'm attempting to incorporate it into Codeigniter. I have been able to get it worki ...

Using Angular 2 to Invoke Functions in Different Components

In my code, I am attempting to invoke a function from another component within a component. Here is an excerpt of my constructor logic: constructor( private http: Http, private appComponent: AppComponent ) { this.setUrl(); } setUrl() { i ...

Implementing image change on dropdown selection using jQuery click event

I'm new to Jquery and JavaScript. I have a dropdown in my Keen template that displays 2 flags. I want to be able to click on the dropdown and select the corresponding flag. Most of the examples I found online use the select and options tags, but my co ...

Understanding the scope of variables in JavaScript when using an anonymous function with addEventListener

Upon clicking on each div, an alert will display '1' if div 1 was clicked, or '5' if div 2 was clicked. This code has been simplified for ease of use in a larger application. <html> <head> <style type="text/css"> #div ...

transforming a two-dimensional array into an object array using JavaScript

Below is a comparison between a two-dimensional array code: var questions = [ ['How many states are in the United States?', 50], ['How many continents are there?', 7], ['How many legs does an insect have?', 6] ]; and i ...

Variables with a global scope within a module

Is there a way to declare a global variable that can be accessed inside a specific module? For example, if we have a module called "test" with files index.js, test1.js, and test2.js, can we define a variable inside index.js that is accessible in test1.js a ...

Navigating through a complex JavaScript project and feeling a bit disoriented

I recently joined a JavaScript project that was being worked on by a single programmer for the past 6 months. However, this programmer left without providing much explanation. The project is built using Ionic, which I have discovered is primarily used for ...

What are the best scenarios for utilizing (a)synchronous calls?

Currently, I am working on a project for my office as a learning exercise. We have a tradition of bringing food every Monday, so I decided to create a program that displays each person's turn. My webpage can generate a calendar with a spare color colu ...

Why doesn't the Kellum method for CSS image replacement work with button elements?

Recently, I discovered that the kellum method doesn't work as effectively with HTML button elements. Specifically, it does work but requires additional text indent. To sum it up, here is the technique: text-indent: 100%; white-space: nowrap; overflow ...

Embed JavaScript locally within an iframe HTML

When attempting to add HTML code within an iframe to showcase data, everything works as expected. However, the issue arises when trying to include any JavaScript within the iframe, as it doesn't seem to be recognized locally. Below is the example cod ...

Allowing users to easily copy and paste within expansion panels

Currently, I am exploring the possibilities of utilizing the ExpansionPanel component provided by Material-UI. However, I am encountering a challenge in enabling text selection on the ExpansionPanelSummary component to allow users to Copy and Paste text ...

Tips for implementing a jQuery mouseleave function for multiple div elements sharing the same id

I am facing an issue with my website where multiple divs share the same id. I need to implement a mouseleave function for all of these divs that have this specific id. Within my $(document).ready function, I currently have the following code... $('#m ...

``Is there a way to successfully pass state and its corresponding setter to a tanstack table ColumnDef

I am working with a ColumnDef that looks like this: export const columns: ColumnDef<Dispute>[] = [ { id: 'select', header: ({ table }) => ( <Checkbox checked={table.getIsAllPageRowsSelected()} onChecke ...