简体   繁体   中英

Using 'styled()' MUI utility with additional props (Typescript)

I'm working on a new project with Material UI v.5. I'm using styled() utility here (not styled-components) to style and create simple UI components. The project is in typescript. I have a lot of difficulties now because I don't know if and how I can pass props to such components. For example, I have component like this:

import { styled } from '@mui/system';


const InputField = styled('input')(({ width }) => ({
  width: width
}));

and I want to use it in this way:

return <InputField width={100}>

but it gives me an error:

Property 'width' does not exist on type '{ theme?: Theme; as?: ElementType<any>; sx?: SxProps<Theme>; } & ClassAttributes<HTMLDivElement> & HTMLAttributes<HTMLDivElement> & { ...; }'.ts(2339)

So my question is: how can I provide additional props for such an MUI-styled component and is it even possible?

You can add the generic type parameter to the returned function of styled like this:

type InputProps = {
  width: number
}

const InputField = styled('input')<InputProps>(({ width }) => ({
  width: width
}));

代码沙盒演示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM