Color Toggle Button in React

Attempting to adjust the color attribute for ToggleButton in React.

Desiring to achieve something like

<ToggleButton color='primary' />

The current API for ToggleButton does not support this feature. A workaround I discovered involves overriding the CSS class of MuiToggleButton.

const theme = createMuiTheme({
    overrides: {
        MuiToggleButton: {
            root: {
                color: 'rgba(50, 72, 86, 0.38)',
                '&$selected': {
                    backgroundColor: 'rgba(50, 72, 86, 0.12)',
                    color: 'rgba(50, 72, 86, 1)',
                    '&:hover': {
                        backgroundColor: 'rgba(50, 72, 86, 0.15)',
                    },
                },
            },
        },
    },
}

This solution impacts all instances of ToggleButton, which may pose issues in certain scenarios.

Answer №1

To add a unique touch to your project, consider creating a personalized Toggle component and selecting the color from the theme that fits best.

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import ToggleButton from "@material-ui/lab/ToggleButton";
import ToggleButtonGroup from "@material-ui/lab/ToggleButtonGroup";

const useStyles = makeStyles((theme) => ({
  root: (props) => {
    return {
      color: theme.palette[props.color].main
      // You can add other individual styles here
    };
  }
}));

function MyToggleButton(props) {
  const { color, ...other } = props;
  const classes = useStyles({ color });
  return <ToggleButton classes={classes} {...other} />;
}

export default function CustomColorToggle() {
  const [color, setColor] = React.useState("primary");
  const handleColor = (e, value) => setColor(value);
  return (
    <ToggleButtonGroup
      onChange={handleColor}
      value={color}
      exclusive
      aria-label="text alignment"
    >
      <MyToggleButton color="primary" value="primary">
        Primary
      </MyToggleButton>
      <MyToggleButton color="secondary" value="secondary">
        Secondary
      </MyToggleButton>
    </ToggleButtonGroup>
  );
}

Click this link for additional details!

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

Embed HTML code into a React/Next.js website

I've been given the task of enhancing the UI/UX for an external service built on React (Next.js). The company has informed me that they only allow customization through a JavaScript text editor and injecting changes there. However, I'm having tro ...

A guide to importing and utilizing images within next.js

I attempted to import an image using the code below, but encountered an error: import Image1 from '../public/IconGBANTQualifiedLeads.png' The error message reads: ./public/IconGBANTQualifiedLeads.png Module parse failed: Unexpected character ...

Unusual behavior exhibited by the React useEffect Hook

After implementing the useEffect hook in React, I am noticing an unusual output on the browser. The counter, which is supposed to increment every 1 second, gets stuck after reaching 10. If you could take a moment to review the code and test it on any onlin ...

Transform routeParams from string to numerical format

Currently, I am working on a straightforward project where I need to retrieve data based on the id number using "routeParams". However, I encountered an issue because the "routeParams" is in string format and I actually need it to be converted to a numbe ...

What is the best way to retrieve the real image from an image path within an HTTP response?

I am having trouble displaying an image in response to my http request. The image path provided looks like this: { poster-path: /heb234gdb.jpg } I have tried various methods such as appending the path to the original http request, using it with the ma ...

What is the best way to customize material components using styled components?

What is the best approach to override material components with styled components, considering that material-ui component classes typically have higher priority than styled-component classes? Is using the !important flag the most effective solution? <bu ...

Step-by-step guide on writing to a JSON file using Node.js

I am currently developing a Facial Recognition web application using React for the frontend and Node.js for the backend. You can find more information about my project here. So far, I have completed the frontend part where users manually add 128-d descript ...

What is the best way to utilize withStyles in order to render a React component?

My question doesn't concern exporting, but rather how to return a React object with injected CSS. I am attempting to achieve the following: return ( withStyles(this.props.style)(<Component {...params}/>) ); The goal is to return Component wit ...

What is causing the .btn-primary class to be implemented despite not being utilized in any way?

I'm puzzled as to why the .btn-primary class is being used here instead of .btn-outline-* which should display with the correct background color. The current bluish background seems out of place. import React from "react"; import Button from ...

Innovative React-driven interface for creating web forms with interactive workflows, including the capability to build multi-page forms

I have experience with react-jsonschema-form, but my requirements are more advanced. I am in need of the ability to specify multi-page forms and establish a workflow between them, such as conditional logic, sub flows, and navigation forward and backward. ...

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 ...

How to enhance a class in JavaScript by adding a dynamic property

Within my code, I've defined a class which looks like this: class classA { id: number; name: string; constructor(data){ this.id = data?.id || 0; this.name = data?.name || ''; } } What I aim to do now is add ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

Error encountered when trying to access children components in Typescript, even though React.FC is being

I am facing an issue with a child component that has the following structure: interface ChildProps extends AnotherInterface{ route: string, exitAction: ActionCreatorWithoutPayload, } const ChildComponent:FC<ChildProps> = ({title, shape, rout ...

Saving moveable objects on a Kanban board to firebase

As part of my project, I have developed a Kanban Board with 3 columns - To Do, Doing, and Done. Each column is populated with tasks, and I have successfully linked actions such as adding, deleting, and modifying tasks and columns to Firebase. However, ther ...

Is there a way to retrieve the total count of the selected options using Autocomplete in material-ui?

Is there a way to show the total count of chosen options using the Autocomplete feature from material-ui? If so, how can I achieve this? Simply follow these steps: click on Open menu dropdown, open the Autocomplete, select your desired options, and you w ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

How to test onSubmit with react-testing-library on react-final-form

I put together a form using react-final-form, yup, and Material-ui. My testing tools include Jest, and @testing-library/react. Summary: Is there a method to mock and test just the onSubmit function without dealing with the validate functionality? Is there ...

What could be causing my Material UI Divider to appear invisible within a Material UI Container or Paper component?

Hey there! I am absolutely smitten with Material UI - it's incredibly versatile. However, I'm facing a bit of trouble with the Material UI Divider not displaying when nested within either a Container or Paper component. I've looked into it ...

If the token is not present, redirect from the dashboard page in Next.js to the login page

As a newcomer to Next.js, I'm looking for a way to redirect from the dashboard page back to the login page if the userToken does not exist. In ReactJS, accomplishing this is simple. However, when attempting it in Next.js, I encountered an error where ...