0

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?

2
  • I've never seen that being used. Do you have a page that describes this usage? Commented Jan 10, 2023 at 17:33
  • @vera. I am doing that in React-Native all the time. Here is one online example doing it newline.co/30-days-of-react-native/…. I assumed that this is also possible in React. But apparently, its not :) Commented Jan 10, 2023 at 20:42

2 Answers 2

3

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

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

your styles will be also overwritten in this way

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.