Utilizing Typescript to pass props to a material-ui button enclosed in styled-components

After setting up my react project using the typescript template, I decided to style the material-ui Button component using the 'styled' method from the styled-components library as shown below:

import React from 'react';
import styled from 'styled-components';
import Button, {ButtonProps} from "@material-ui/core/Button";

type StyledButtonProps = ButtonProps & { primary?: boolean }


const styledButton = styled(Button)`
  background-color: ${(props: StyledButtonProps) => props.primary ? "palevioletred" : "white"};
  box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
  padding: 7px 14px;

  &:hover {
    background-color: aqua;
  }

  & .MuiButton-label {
    color: #070303;
  }
` as React.ComponentType<StyledButtonProps>

export default styledButton;

Everything seemed to be working fine until I tried to use this Styled button with a boolean value for primary. However, an unexpected warning message appeared when I attempted to implement it like so:

<StyledButton primary={true}>Styled Buton</StyledButton>

The warning message that popped up can be viewed here.

I'm puzzled as to why this warning is occurring. Any suggestions on how to resolve it?

Answer №1

When using styled-components, be mindful that the DOM only accepts string values like primary="true", not boolean values like primary=true. Therefore, make sure to change any instances of true to "true" to ensure proper rendering on the DOM.

If you switch from primary={true} to primary="true", the primary attribute will be correctly displayed in the DOM as shown here: https://i.stack.imgur.com/Ga2Bl.png


However, if you prefer not to render the primary property on the DOM, you can use Transient props to dismiss the warning:

To prevent passing a specific property to the DOM, simply prefix it with a dollar sign ($). This way, styled-components will avoid passing that property to the DOM. Check out the documentation for more information.

<StyledButton $primary={true}>Styled Button</StyledButton>

...

background-color: ${(props: StyledButtonProps) =>
    props.$primary ? "palevioletred" : "white"};
...

For a demo, you can visit the codesandbox link.

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

I often find that jscodeshift consistently avoids processing my JavaScript files

I am currently in the process of updating my react application to the newest version of Material-UI. I came across a migration helper script using jscodeshift within the material UI project. (https://github.com/mui-org/material-ui/tree/master/packages/mate ...

React Native Navigation - Utilizing Duplicates of a Screen

My app (built with react native, redux, and experimental navigation) features deep flows that allow users to navigate to multiple occurrences of the same screen, such as tapping through various profiles. In order to prevent each new instance of the screen ...

Angular - Issue with Function Observable<number> in Development

Currently, I'm working on writing TypeScript code for a component. Within this TypeScript class, I have created a function that is meant to return a number representing the length of an array. My goal is to have this function work like an Observable. ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Bug in Next.js caused by downgrading and then reinstalling the original version of Node

Having to remove the current version of node and downgrade to a later version for another project caused some issues. Once I reinstalled version 20 of node, my Next.js project stopped working! PS C:\Github\portfolio.2.0> npm start > <a ...

Step-by-step guide on implementing virtual scroll feature with ngFor Directive in Ionic 2

I am working on a project where I need to repeat a card multiple times using ngFor. Since the number of cards will vary each time the page loads, I want to use virtual scrolling to handle any potential overflow. However, I have been struggling to get it ...

When the parent element has a fixed position, the child element will no longer maintain its floating property

I'm currently working on a fixed navigation panel that sticks in place while scrolling down. Here is the code I have so far: <header> <a class="logo" href="/">Logo_name</a> <nav> <a href="#">Menu_1</a& ...

Tips for efficiently utilizing Hooks with React Context:

I am currently working on my application and utilizing React Context with the setState function. const userContext = React.createContext([{ user: {} }, () => {}]); const userHook = useState({ user: {} }); <userContext.Provider value={userHook}> / ...

Easiest method to change cursor to 'wait' and then return all elements to their original state

On my website, there are certain CSS classes that define a specific cursor style when hovered over. I am trying to implement a feature where the cursor changes to a "wait" image whenever an AJAX call is initiated on any part of the page, and then reverts b ...

Why does the 401 error continue to persist while attempting to log in using Google Identity service on my Laravel application?

Trying to implement Google authentication services for user authentication. I've already integrated Laravel sanctum to allow users to log in and register successfully. This time, I want to add Google Identity services as an additional authentication ...

When jQuery adds new elements, their CSS may not be applied accurately

One issue I encountered is using jQuery to dynamically add new elements, only to find that the CSS isn't being applied correctly to the newly added element. To illustrate this problem, I created a jsFiddle. In the example, there are differences in sp ...

In the event that the get request fails, go ahead and clear the

Currently facing an issue and seeking a solution: I have a game running that retrieves the state of the game periodically. However, if a user logs out, the game ends but continues to send put requests at the set interval. I am exploring options like setti ...

HTML button failing to connect with CSS stylesheet

I am currently teaching myself CSS and using W3schools for guidance. Recently, I added a button to my website that redirects users to another page upon clicking. Everything functions correctly, but now I want to style the button using CSS. However, despit ...

The mysterious height phenomenon when setting the width of a list item with jQuery

Consider a basic ul and li setup similar to this: <div id="middle"> <ul> <li> <a> bridal </a> </li> //.... </ul> </div ...

creating a randomized location within an HTML element using JavaScript

Trying to figure out how to randomly generate a position within an HTML div. I've come up with a JavaScript function that looks like this: function randomInRange(min, max) { return(Math.floor((Math.random() * (max - min) + 1) + min)); } My ...

There was a TypeError that was not caught in the promise, stating that the function window.showOpenFilePicker is not valid

Encountering TypeError with File System Web API While experimenting with the File System Web API, I keep receiving a TypeError stating Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function. I am unsure of what is causing this issue. ...

Tips for getting free jqgrid to display frozen column borders in the search toolbar

If the actions column has a caption of "Activity" or custom settings and is frozen, the free jqgrid will not display column borders for this column in the search toolbar. Vertical lines do not appear in the search toolbar: Is there a way to resolve this ...

I am having trouble getting my footer to align properly in a vertical position

My goal is to have my li elements remain on the same line, but unfortunately, they are not cooperating (they are aligning horizontally, but that's all). Here is the code snippet: <footer> <div class="container"> <div id="coi ...

Add a pair of assorted div elements to a shared container

I have two different sections with classes named "red" and "blue". By default, these sections are hidden. I want to duplicate them and display them in a single container named "cont". The red button appends the red section and the blue button appends the b ...

How to create a collapsible nested list feature in ReactJs for a single list item

I have been working on creating a collapsible sublist using Material UI and ReactJS by referring to the examples provided in the material-UI list. However, I am encountering an issue where clicking on one list item expands all other list items as well, sim ...