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

My React application is not showing the CSS styles as intended

In my project, I have a component file named xyx.js where I properly imported my scss file './xyz.scss'. Both of these files are in the same folder. Interestingly, when I view the styles using the Chrome scss extension, everything seems to be wor ...

jsonwebtoken does not fetch a token

I've been working on a user registration system using nodejs and sequelize. So far, I've successfully implemented the login and register functionalities. However, I am encountering an issue with getting the token after a successful login. Despit ...

The Ajax request is not being triggered when using a different form submit method

Being a tech enthusiast, I have developed a handy function: function blur_slide_visit_count(){ $.ajax({ type: 'POST', url: 'add_save_slide_visitor_count.php', async: false, data: { fillvalue: fieldAr ...

Is it possible to use Apollo Client when React Hook relies on data that is only available after a Conditional statement?

Seems like there are Order of Operations issues here. I am encountering an error when trying to use a React Hook after a conditional statement: Error: Rendered more hooks than during previous render The React Hook I am using is from a third-party an ...

Is there a way to have incoming messages automatically align to the left or right based on the sender, without using the float property?

I am currently working on a webpage where I want the messages sent by different users to appear in a yellow conversation window based on who sent them - user 1 or user 2. I want it to mimic the messaging layout commonly seen on phones, distinguishing betwe ...

Ways to retrieve data from an AJAX success callback function

Within my front end JavaScript application, I need to execute an ajax request in order to retrieve data from the server. Once this data is acquired, I aim to display it within the view. var retrievedData; $.ajax({ url:"/getDataFromServer.json", ty ...

Updating an AngularJS directive following a service method invocation

My goal is to set up a reusable alert service that can be easily called from anywhere in my application with just: alertService.showAlert('warning', 'something went wrong!'); One example of where I want to use this is after an AJAX ca ...

distinguish different designs for individual components in Angular 5

My project is divided into two main parts: one for public web pages and the other for an admin control panel. Each part has its own set of CSS and javascript files for custom templates. If I include all CSS and js files in index.html, they all load at the ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

Using Angular's filter service within a controller

Just starting out so please be kind!! Encountering an issue with Angular 1.3 while using a Stateful Filter within a controller. In brief, when utilizing the $filter('custom')(data) method instead of the {{ data | custom }} method - and the cust ...

Guide to crafting an effective XHR request using AJAX

Here's a snippet of my basic web page: <!DOCTYPE html> <html> <head> </head> <body onload="start()"> </body> </html> Below is the XMLHttpRequest function I've implemented: function start(){ / ...

Is it possible to manage the form submission in React after being redirected by the server, along with receiving data

After the React front-end submits a form with a POST request to the backend, the server responds with a JSON object that contains HTML instead of redirecting as expected. How can I properly redirect the user to the page received from the server? For inst ...

Prevent Second Division from wrapping around floated Division

I am running into a minor issue with the positioning of a div in my current project. +------------------------+ |+-------+ ~~~~ TITLE| <--how can I prevent text from wrapping around || | ~~~~~~~~~~~~~ |\ on the left ...

Adding CSS classes through the .addClass method - A guide on utilizing linked CSS files

I came across this code snippet and I have a quick question. $(window).scroll(function() { var y_scroll_pos = window.pageYOffset; var scroll_pos_test = 150; // adjust as needed if(y_scroll_pos > scroll_pos_test) { $( "#cssmenu" ).addCl ...

Is it acceptable to designate the db instance as a global variable so that it is always accessible without requiring the "require" statement in Node.js?

I am just starting my journey with "node js" and I am currently working on a program that requires a database model similar to "wpdb" in WordPress. Should I create it as a global variable or use the "require" statement only when needed? Your help in provi ...

Adjusting the structure of React Native Flex:1 to optimize performance and organization

In the layout above, the red component should fill the entire screen and the button should be positioned at the bottom. `<SafeAreaView style={{flex: 1, backgroundColor: 'red'}}> //red component <TouchableOpacity //purple component ...

Exploring the main directive flow, attaining access to `ctrl.$modelView` in AngularJS is

Four Methods Explained: What Works and What Doesn't I recently created an angular js directive where I encountered difficulty accessing the ctrl.$modelValue in the main flow. In my quest to find a solution, I came up with four potential methods, eac ...

Utilizing node-json2html, generate individual HTML tables for each record

I need assistance in consolidating my JSON data into a single HTML table, instead of generating separate tables for each record through my current transformation process. var data=[{"name":"aa","mid":"12345","user":"a123","password":"a@123"},{"name":"bb" ...

The variable 'string' has been declared, but it is never utilized or accessed

Currently delving into Typescript and facing an early error. Despite following a tutorial, I'm encountering multiple errors that I have attempted to comment out. Would greatly appreciate it if someone could shed some light on why these errors are occu ...

Replicating a Bootstrap element without transferring all event listeners

Recently, I posted a query on Stack Overflow regarding the cloning of a bootstrap element while excluding the copied event listener. The solution provided was to refrain from passing true to the clone() function. Upon further reflection, I've realize ...