The art of replacing material-ui styles with styled components

As a newcomer to UI material design, I am eager to create my own customized Button Component using styled-components.

I am facing a challenge in overriding the CSS based on different button variations such as "primary" or "secondary".

You can find my code on codesandbox.io

import React from "react";
import PropTypes from "prop-types";

import { CButton } from "./styles";

const CustomButton = ({ children, color }) => {
  return (
    <div>
      <CButton variant="contained" color={color}>
        {children}
      </CButton>
    </div>
  );
};

CustomButton.propTypes = {
  children: PropTypes.node,
  color: PropTypes.oneOf(["primary", "secondary"])
};

export default CustomButton;
import styled, { css } from "styled-components";
import Button from "@material-ui/core/Button";

export const CButton = styled(Button)`
  height: 80px;

  ${({ color }) =>
    color === "primary"
      ? css`
          background-color: green;
        `
      : color === "secondary" &&
        css`
          background-color: yellow;
        `}
`;

import React from "react";

import CustomButton from "./CustomButton";

const App = () => {
  return (
    <div>
      <div
        style={{
          marginBottom: "10px"
        }}
      >
        <CustomButton color="primary">Primary</CustomButton>
      </div>
      <div>
        <CustomButton color="secondary">Secondary</CustomButton>
      </div>
    </div>
  );
};

export default App;

https://i.stack.imgur.com/YUsQf.png

Can you guide me on how to ensure that my custom styling takes precedence over the ui-material?

Your assistance is greatly appreciated.

Answer №1

There is a helpful example in the material-ui documentation that demonstrates how to achieve this using styled-components: https://material-ui.com/guides/interoperability/#styled-components

You may be overlooking the use of the StylesProvider, which enables your styles to take precedence over the default material styles. This should address... The conditional aspect in your scenario doesn't appear to be the issue at hand.

const MyStyledButton = styled(Button)`
  background-color: red;
  color: white;
`;

export default function App() {
  return (
    <StylesProvider injectFirst>
      <div className="App">
        <MyStyledButton color="primary">Foo</MyStyledButton>
      </div>
    </StylesProvider>
  );
}

If you'd like to explore further, check out the following codesandbox: https://codesandbox.io/s/infallible-khorana-gnejy

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

Blog Format Featuring Side-by-Side Columns

Is there a way to achieve horizontal columns that don't cut off articles and flow seamlessly into the next column? I want the columns to have varying heights, such as Post A at 60% height, followed by Post B at 40% height, then Post C at 30%, and fina ...

Import necessary styles into the shadow DOM

Embracing the concept of shadow dom styles encapsulation is exciting, but I wish to incorporate base styles into each shadow dom as well (reset, typography, etc). <head> <link rel="stylesheet" href="core.css"> ... </h ...

angular click triggers the following content

How can I make the following content appear when clicked? I have a list of content that displays up to 20 items, but I want to show the rest when clicked. I have created the nextMovieList method for this purpose. import { Component, OnInit } from ' ...

Guidelines on creating actionable functions using JavaScript

Having trouble connecting the form to the database and looking for a solution. This is the HTML form that I've been working on, attempting both POST and GET methods. <form id="register" action="script/register.js" method="post"> <label for= ...

The design I created includes a horizontal scroll feature and certain elements are not properly aligned in the

Oh man, I'm really frustrated right now. I want all my elements to be centered horizontally on smaller devices, but some of them are slightly off to the side. And to top it off, there's a horizontal scroll appearing - it's like something is ...

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

Understanding the Process of Accessing Array Values in Immutable.js

I'm feeling a little puzzled and struggling to figure this out. Let's say I have the following code: const AnObj = Immutable.Map({ a : "a", b : Immutable.List.of( a, b, c, Immutable.Map({ a : "a" }) ) }); When working with Immu ...

Is there a way to modify a specific item within a useState Array in Reactjs?

Having a useState hook that stores data in the following structure: const [orderData, setOrderData] = useState({ demoData1: '', demoData2: '', demoData3: '', demoArrayData: [{itemName: '', itemNumber: ...

Encountering a "file or directory not found" error during the installation of ply using

I recently stumbled upon an interesting project for testing Rest APIs. I was in the process of installing ply from https://github.com/ply-ct/ply npm install ply-ct --save-dev Encountered this error, wondering if anyone has a solution npm WARN saveError EN ...

How to use the v-model to round up a number in Vue.js

I need to round up a number in my input field: <b-form-input id="amount_input" type="number" v-model="Math.ceil(form.contract.reward_cents / 100)" :state="validate(form.contract.reward_cents)"/> ...

Show segments of video stream on page using node.js

I am currently exploring Node.js and trying to understand how streams work, so please bear with me if I seem a bit unclear. After reading some beginner notes on streams, I decided to test it out. In my project files, specifically in public/images/videos/S ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...

Cookie Multitree: An Innovative JsTree Solution

Hello everyone, I am currently using jstree and have come across a couple of issues with having multiple trees on the same page. Here are my two problems: 1) I am looking to implement cookies to keep track of which nodes are open in each tree. I attempted ...

The method of pausing a function until the result of another function is returned

There is a function named 'updateProfile()' that includes a condition, which checks for the value of variable 'emailChangeConfirm' obtained from another function called 'updateEmailAllProcessing()'. The issue lies in the fact ...

What are some ways to slow down the speed of a canvas animation?

I am currently working on an animation project using JavaScript and canvas. I have a reference fiddle where objects are generated randomly and fall from the top right corner to the bottom left corner, which is fine. However, the issue is that the objects a ...

Console displays null as the attribute value

When I check the console, I notice that the data-postid attribute is displaying 'null'. What could be causing this issue? I would like to view the data-id in the console when clicking on the button with the id modal-save. I have reviewed my cod ...

How to style TextInput to display dollar amounts when using onChangeText and Redux in React Native

Struggling to format number input in a TextInput using the onChangeText function in React Native with Redux. Tried using .toFixed(2) function, but encountering an issue where it interprets the next digit as the first decimal and rounds back to 0 due to Re ...

Numerous hyperlinks leading to different products within the same image

I am looking for a solution to create clickable links on a picture that contains multiple items (3 in my specific case, as shown in the image above). Currently, I am using position:absolute to place links on each item, but this method is causing overlap ...

Navigating a roster of users in JavaScript

I'm dealing with a collection of user data stored in an array accountsade: [ { id: 0.4387810413935975, name: "Adrian", password: "345", userName: "nathanael" }, { id: 0. ...

Activate a function for a targeted ajax request within a global $.ajax event

I have a series of 3-4 ajax calls that are scheduled to be executed at some point. In one of these calls, I want to activate a function on the global ajaxSend event. This particular ajax call may not be the first or last in the sequence. However, when I at ...