Implementing default props in styled components within material-ui

Is there a way to set default props on custom styled components in MUI? Right now, I find myself adding maxWidth="sm" to every instance which I'd prefer to have predefined.

const StyledContainer = styled(Container)(({ theme }) => ({
  marginTop: theme.spacing(2),
}));

...

<StyledContainer maxWidth="sm" /> // current implementation

<StyledContainer /> // desired outcome

Answer №1

To simplify the code, you can encapsulate the functionality within a separate component.

import Button, { ButtonProps } from "@mui/material/Button";
import styled from "@mui/material/styles/styled";

export type MyComponentProps = ButtonProps & {
  myNewVariable: string;
};

function MyComponentImpl(props: MyComponentProps) {
  return <Button variant="outlined" {...props} />;
}

export const MyComponent = styled(MyComponentImpl)(
  ({ myNewVariale, theme }) => ({
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    padding: theme.spacing(2),
  }),
);

Answer №2

Try using attrs with styled components for easy customization. The example below demonstrates setting the "sm" variant container as the default.

Find more information in the documentation: https://styled-components.com/docs/api#attrs

const CustomContainer = styled(Container).attrs((props) => ({
  maxWidth: props.maxWidth || "sm"
}))(({ theme }) => ({
  marginTop: theme.spacing(2)
}));

const App = () => <CustomContainer>1</CustomContainer>;

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

Steps to add annotations to a class descriptor:

Can you help me with the correct way to annotate this piece of code? export class TestCls { static SomeStaticFn(): TestCls { // Do some stuff... // Return the class descriptor for a "fluid usage" of SomeStaticFn return TestCls ...

Clickable MUI Card: Enable full card functionality for mobile devices only, keeping desktop interaction restricted

I'm currently utilizing the MUI card component to construct a layout. When viewing on mobile devices, I want the entire card to be clickable. However, on desktop screens, I prefer to have a button instead and make the card itself non-clickable. Here& ...

What is the best way to simulate a function within an object using Jest and Typescript?

I am currently working on a function that calls the url module. index.svelte import {url} from '@roxi/routify'; someFunction(() => { let x = $url('/books') // this line needs to be mocked console.log('x: ' + x); }); ...

Avoid installing @types typings in dependencies

Can I prevent global typings from being included in installed dependencies? I recently installed a local dependency, which led to the node_modules folder of that dependency being copied over. Within this node_modules folder are @types typings that clash w ...

Waiting patiently for the arrival of information, the dynamic duo of Angular and Firebase stand poised and

Here is the given code snippet: signIn(email, password) { let result = true; firebase.auth().signInWithEmailAndPassword(email, password).catch(error => result = false); waits(100); return result; } I have a ...

Exploring the power of Vue 3 and Vuex with Typescript to access class methods

Can Vuex state be used to access class methods? For example, in this scenario, I am attempting to invoke fullName() to show the user's formatted name. TypeError: store.state.user.fullName is not a function Classes export class User { constructo ...

Filter multiple columns in an Angular custom table with a unique filterPredicate

Looking to develop a versatile table that accepts tableColumns and dataSource as @Input(). I want the ability to add custom filtering for each table column. Currently, I've set up the initialization of the table FormGroup and retrieving its value for ...

Multiple keyup events being triggered repeatedly

Currently, I am developing an Angular 4 application. Within my component's HTML, there is a textbox where users can input text. As soon as the user starts typing, I want to trigger an API call to retrieve some data. The current issue I am facing is t ...

Error: 'process' is not defined in this TypeScript environment

Encountering a typescript error while setting up a new project with express+ typescript - unable to find the name 'process'https://i.stack.imgur.com/gyIq0.png package.json "dependencies": { "express": "^4.16.4", "nodemon": "^1.18.7", ...

Challenges arising from the usage of Vue component state in TypeScript

I'm encountering an issue with a basic Vue component. I'm attempting to trigger a rerender of v-if="isTouched" by setting the setter (via the touch event). Vue dev tools indicate that the _isTouched variable is showing as "undefined". My underst ...

What is the process for implementing custom color props with Material-UI v5 in a React TypeScript project?

Looking to enhance the MUI Button component by adding custom color props values? I tried following a guide at , but encountered errors when trying to implement it in a custom component. The custom properties created in createPalette.d.ts did not work as ex ...

Alternating the tooltip icon based on the field's condition

Looking for a way to create a tooltip for an input field that involves changing icons based on certain conditions. An example scenario is the password field in a registration form. Seeking advice on the best approach to achieve this. Currently, here' ...

DOCKER: Encounter with MongooseError [MongooseServerSelectionError] - Unable to resolve address for mongo

I am currently attempting to establish a connection between MongoDB and my application within a Docker container. Utilizing the mongoose package, here is the code snippet that I have implemented: mongoose.connect("mongodb://mongo:27016/IssueTracker", { us ...

The incorrect argument is being used to infer the generic type

I have implemented the NoInfer feature from the library called ts-toolbelt. However, it seems that the example provided below does not reflect its intended effect. In this scenario, the generic type is deduced from the util function as soon as it is intr ...

Having trouble passing a React Router Link component into the MuiLink within the theme

The MUI documentation explains that in order to utilize MuiLink as a component while also utilizing the routing capabilities of React Router, you need to include it as a Global theme link within your theme. An example is provided: import * as React from & ...

Assigning different data types with matching keys - "Cannot assign type '...' to type 'never'."

I have a question regarding my application, where I am utilizing values that can either be static or functions returning those values. For TypeScript, I have defined the static values along with their types in the following manner: type Static = { key1: ...

The declaration file for the 'vimeo' module was not located

My current setup includes typescript v^3.4.2, in an express app (^4.14.1), using node v11.3.0. During the build process for typescript, I encountered this error: Could not find a declaration file for module 'vimeo'. '/Users/me/Code/MyServe ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Unknown error occurred in Eventstore: Unable to identify the BadRequest issue

I'm encountering an error while using Eventstore, specifically: Could not recognize BadRequest; The error message is originating from: game process tick failed UnknownError: Could not recognize BadRequest at unpackToCommandError (\node_modul ...

'The object literal does not match the type of parameter' error is displayed

Encountering an issue with object literal type. interface OptionalFoo { foo?: number; } interface Bar {} function foobarFn(foobar: OptionalFoo & Bar) {} foobarFn({ bar: 1 }); // error foobarFn({ bar: 1 } as { bar: number }); // ok foobarFn({ ba ...