Pass style as a prop with React and TypeScript

Learn how to add the correct TypeScript type for a style prop in React.
October 10, 2022React
2 min read

If you're developing React apps with TypeScript, you may run into a situation where you need to find the correct type to use for a style prop in your components.

The CSSProperties type can be used to pass CSS styles as a style prop to a component in React. CSSProperties is the correct TypeScript type for a style object containing CSS property names and their corresponding values.

Using a style prop

Let's take a look at a simple example of a React Button component. We want this Button component to have a style prop, where it can receive a style object of CSS properties.

We will make this style prop an optional one, so that a Button instance can be used without being forced to pass a custom style object to it.

App.tsx
import React, { ReactNode, CSSProperties } from 'react';

type ButtonProps = {
  style?: CSSProperties;
  children: ReactNode;
};

// our Button component
const Button = ({ style, children }: ButtonProps) => {
  return <button style={style}>{children}</button>;
}

// our main App component
const App = () => {
  const buttonStyle = {
    padding: '2rem', 
    color: '#fff', 
    backgroundColor: 'blue',
    fontWeight: 'bold',
  };

  return (
    <>
      <h1 style={{ color: '#333' }}>Hello world</h1>

      <Button style={buttonStyle}>
        Add to cart
      </Button>
    </>
  );
};

export default App;

Checking that the right type was used

In Visual Studio Code, if we right-click on style attribute of the h1 tag in the code above, we'll notice that the type definition for style is in fact the one that we used. This confirms that we used the correct type.

style?: CSSProperties | undefined;

React.CSSProperties

Another way that we can make use of CSSProperties is to refer to it as React.CSSProperties and then remove the explicit CSSProperties reference from the import statement.

// Before
// import React, { ReactNode, CSSProperties } from 'react';

// After
import React from 'react';

type ButtonProps = {
  style?: React.CSSProperties;
  children: React.ReactNode;
};

New
Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.