Last updated: Feb 29, 2024
Reading time·2 min
Use the React.CSSProperties
type to pass CSS styles as props in React
TypeScript.
The CSSProperties
type is used to type the style object that consists of CSS
property names and values.
import React from 'react'; type ButtonProps = { // 👇️ type as React.CSSProperties style: React.CSSProperties; children: React.ReactNode; }; function Button({style, children}: ButtonProps) { return <button style={style}>{children}</button>; } const App = () => { return ( <div> <Button style={{ padding: '2rem', fontSize: '3rem', backgroundColor: 'lime', }} > Click </Button> <h2 style={{fontSize: '3rem'}}>Hello world</h2> </div> ); }; export default App;
We typed the style
object as React.CSSProperties
.
Button
component, you will get autocomplete for property names.You can figure out what the expected type for a specific prop is by using your IDE.
In most IDEs, you will be able to hover over the prop and see its value.
style
prop and then clicked "Go to Definition".The definition of the style
prop shows that its type is either CSSProperties
or undefined
.
If you need to pass a function as props in React TypeScript, check out the following article.
You might also need to extend an HTML element in a component's props.
// 👇️ extend button props interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { style: React.CSSProperties; children: React.ReactNode; } function Button({style, children}: ButtonProps) { return <button style={style}>{children}</button>; } const App = () => { return ( <div> <Button style={{ padding: '2rem', fontSize: '3rem', backgroundColor: 'lime', }} > Click </Button> <h2 style={{fontSize: '3rem'}}>Hello world</h2> </div> ); }; export default App;
The example shows how to extend a button element in the props of our custom component.
We used the React.ButtonHTMLAttributes
type to extend a button element in the
component's props.
You can add your custom props to the interface and your component can be passed any of the element-specific props.
You can read more about extending an HTML element in a component's props in React TypeScript in the following article.
I've also written a detailed guide on how to use create-react-app with TypeScript.
You can learn more about the related topics by checking out the following tutorials: