Tips on avoiding the passing of props to a styled component within your code

I'm currently working on customizing the styling of Material UI components by utilizing props. I want to create a unique composition solely based on changing styles through props.

import { Typography } from "@mui/material";
import { styled } from "@mui/system";

type MyTypographyExtraProps = { isEven?: boolean };

export const MyTypography = styled(Typography)<MyTypographyExtraProps>(
  ({ theme, isEven }) => `
   color: ${theme.palette.common.black};

   ::after {
      content: "";
      display: inline-block;
      height: ${theme.spacing(2)};
      width: ${theme.spacing(2)};
      border-radius: ${theme.spacing(2)};
      background-color: ${theme.palette[isEven ? "success" : "error"].main};
   }
  `,
);

Using the styled function, my isEven prop gets passed to the Material Typography component which then passes it to the DOM, resulting in a warning message:

Warning: React does not recognize the isEven prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase iseven instead. If you accidentally passed it from a parent component, remove it from the DOM element.

I'm wondering if there's a way to bypass the type declaration before it reaches the typography element to avoid this warning.

One solution could be creating an additional component to strip out the props in that layer, but I'm interested in exploring any potential methods to achieve this without adding another component.

Answer №1

According to the documentation provided on how to customize materials, there is a suggested function for excluding certain props from being passed down.

shouldForwardProp: This function specifies which props should be forwarded to styled components.

export const MyTypography = styled(MuiTypography, {
  shouldForwardProp: prop => prop !== "isEven", // ⭐
})<MyTypographyExtraProps>(
  ({ theme, isEven }) => `
   color: ${theme.palette.common.black};

   ::after {
      content: "";
      display: inline-block;
      height: ${theme.spacing(2)};
      width: ${theme.spacing(2)};
      border-radius: ${theme.spacing(2)};
      background-color: ${theme.palette[isEven ? "success" : "error"].main};
   }
  `,
);

NOTE: shouldForwardProps and skipSx props may not align perfectly if you want to prevent both sx and other props at the same time.
For further details, refer to this issue on GitHub

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

Check for duplicates within 2 arrays by implementing a filtering process

I am trying to figure out how to compare two arrays to determine if there are any duplicates within them. const result = this.specialRange.filter(d => !dayMonth.includes(d)); What I have attempted so far just returns the entire array back to me, but I ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

Developers beware: A functional component is generating a warning during development. Remember, function components do not support refs. Perhaps you intended to utilize React.forwardRef

Hey there! I have a question about a plugin that I've created and integrated into an application called HRnet (React 18). During development, I'm not encountering any warnings on the plugin side. However, when developing on the application side, ...

Refreshing RadioGroup selection in React.js

Currently, I am in the process of developing a quiz application using React. In order to create multiple-choice questions, I have integrated Material-UI for radio button inputs. However, I am encountering an issue where the selected buttons are not clearin ...

The global declaration of Typescript is only accessible within the node_modules/@types directory

Scenario As I develop an npm package using Typescript, I include types that are shipped alongside the library in the following structure: my-package |- index.js |- index.d.ts |- package.json The index.d.ts file includes global declarations like: declare ...

Tips for extracting the value and ID of selected checkboxes from a multi-select using Material-UI

I am currently utilizing the MUI select component with multi-select functionality. I have a JSON array below for rendering the multi-select options. Is there a method to retrieve both the ID and value of the selected item? For reference, you can view the ...

Issue with React MUI V5 causing theme not to display properly within shadow-root element

After trying to attach the shadow root using the MUI createTheme function, I encountered rendering issues. Despite following the instructions in this helpful guide on the MUI website, my problem persists. // App.js const cache = createCache({ key: ' ...

Combining Material UI Select component with Formik

I have a personalized Material UI multiple select input feature. Through customization, it can be preloaded with initial values obtained from a database, presenting them as selected items in the input field. The functionality also includes a function calle ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

Mental stability groq fails to provide the requested information

Having difficulty using Groq to fetch data. All other Groq queries work fine, except this one. When manually setting the $slug variable, the data I'm trying to query works with the Sanity Groq VS plugin but returns undefined in my web app. Query: exp ...

What is the best way to empty a TextField in a React application?

Greetings to all! I could use some help figuring out how to clear a TextField after clicking the icon. Any suggestions would be greatly appreciated. Thanks! const [filteredLocations, setFilteredLocations] = useState(locations); const clearSearch = () =& ...

Issue with 'else if' statement in React Typescript: Unneeded 'else' block following 'return' statement

I am encountering an issue with the else if statement below. Even after removing the last pure Else statement, I am still getting an error on ElseIf from Lint. How can I fix this problem? Error message: Unnecessary 'else' after 'return&apo ...

Challenges arise when trying to access environment variables using react-native-dotenv in React

I am currently working on two separate projects, one being an app and the other a webapp. The app project is already set up with react-native-dotenv and is functioning as expected. However, when I attempt to use the same code for the webapp, I encounter an ...

What strategies can I employ to create test cases for the untested code within useEffect and dispatch functions?

Just beginning my journey in writing tests, so this is all new to me. Executing the command below: $ yarn test:coverage This is the output I get: https://i.stack.imgur.com/cqAwo.png I need to retrieve a list of Models through dispatch when the dropdo ...

Is it possible to achieve real-time two-way data binding in a reactive form by passing values from one formgroup to another formgroup? If so, how

There are 2 FormGroups named orderForm and parcelForm on a page. The parcelForm is generated dynamically within a FormArray. In the parcelForm, there are FormControls like net_weight and gross_weight, while the OrderForm has FormControls such as total_net_ ...

React: Issue with Intersection Observer not triggering state updates

Looking to implement an endless scroll feature using intersection observer, where new content appears as the user reaches the bottom. Here's a simplified version of the code: function App() { const ids = [1, 2, 3, 4, 5, 6] const [ProductIds, setPr ...

Encountering issues while attempting to modify the route from a particular Component

I have encountered an issue with changing routes in React from a specific component to another. Switching between '/' and '/login' works fine, but when the active route is '/menu-management', clicking on the Link causes an err ...

Tips for notifying the user about incorrect login credentials in Ionic 3

I'm attempting to implement a notification system using showAlert to inform users when they enter an incorrect email or password, but I'm having difficulty achieving this using try and catch statements Would it be feasible for me to use try and ...

Tips on how to postpone the rendering of a select component in material-ui

Upgrading to @material-ui/core 4.11.2 caused warnings with my select components due to data not being available during rendering. You can view the issue on github: https://github.com/mui-org/material-ui/issues/24041 To resolve this, the availability of l ...

What is the best way to allow the browser to either download a file or open it in a new tab based on what is feasible? (while maintaining the actual file

Currently in my web application, which utilizes Angular for the front-end and .Net Core for the back-end, there is a page where users can click on server-side stored files. The desired behavior is for the file to open directly in a new tab if the browser a ...