skip to Main Content

I want to declare a React.CssProperties prop to my component, but utilizing PropTypes. So far, I can make it works with PropTypes.object. But then when I use the component, I cannot get css property type hint (ex. style like width, color, etc). Also, I have to manually cast it to React.CssProperties when assigning the prop to element.

Is there a way to declare a type like React.CssProperties with PropeTypes in Typescript?

import React from 'react';
import PropTypes, {InferProps} from "prop-types";

const propTypes = {
  text: PropTypes.string,  
  style: PropTypes.object,
};
type Props = InferProps<typeof propTypes>;

const MyButton = ({text, style}:  Props) => {
  return (
    <button style={style as React.CSSProperties} />
  )
})

import React from 'react';
const App = () => {
  return (
    <MyButton style={{width: '100px'}}>{text}</button> // no type hint in IDE when typing width, color..etc
  )
}
export App

2

Answers


  1. Here is the optimize code:

    import { CSSProperties, FC } from 'react';
    
    interface MyButtonProps {
      text: string;
      style?: CSSProperties;
    }
    
    const MyButton: FC<MyButtonProps> = ({ text, style }) => {
      return (
        <button style={style}>{text}</button>
      );
    };
    
    export default MyButton;
    

    Here is the result:
    Expected Result

    Login or Signup to reply.
  2. you not need to import propTypes from propTypes. simply use type

    import React from 'react';
    
    
    type PropTypes = {
      text: string,  
      style: any,
    };
    
    const MyButton = ({text, style}:  Props) => {
      return (
        <button style={style as React.CSSProperties} />
      )
    })

    Hope this help you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search