Home > Back-end >  Pass array of objects to style prop in React and TypeScript
Pass array of objects to style prop in React and TypeScript

Time:01-11

In JavaScript React I would do this to "merge" several styles:

const customStyle= {
    fontWeight: 'bold'
};

<p 
    style={[{fontStyle: 'italic'}, customStyle]}>
    {Some Text....}
</p>

However, when I try this in a TypeScript React project I get the following:

TS2322: Type '({ fontWeight: string; } | { fontStyle: string; })[]' is not assignable to type 'Properties<string | number, string & {}>'.
   Types of property 'filter' are incompatible.
     Type '{ <S extends { fontWeight: string; } | { fontStyle: string; }>(predicate: (value: { fontWeight: string; } | { fontStyle: string; }, index: number, array: ({ fontWeight: string; } | { fontStyle: string; })[]) => value is S, thisArg?: any): S[]; (predicate: (value: { ...; } | { ...; }, index: number, array: ({ ...; } ...' is not assignable to type 'Filter | undefined'.

This array construct comes in quite handy, because the order of the elements is important. With customStyle I could overwrite everything I defined in the object {fontStyle: 'italic'} before...

How would I pass several styles to the style prop of an HTML element?

CodePudding user response:

why don't you use spread operators? like this:

style={{fontStyle: 'italic', ...customStyle}}

your styles will be also overwritten in this way

CodePudding user response:

you'd need to reduce your array to a single object:

style={[{fontStyle: 'italic'}, customStyle].reduce((carry, current) => ({ ...carry, ...current}), {})}

CodePudding user response:

The style propertie in react can receive React.CSSProperties | undefined, an object of type React.CSSProperties or undefined but not an array.

You can combine the two objects in the array in a single one with a reducer, or use the spread operator of two objects both the type React.CSSProperties.

To "overwrite" one object just place the spread operator after, all repeated keys will be overwritten.

const customStyle: React.CSSProperties = {
  fontStyle: "normal",
  fontWeight: "bold"
};

<p
  style={{
    fontStyle: "italic",
    ...customStyle
  }}
>
  Some text
</p>

Sandbox

  • Related