Is it correct to add styles like properties in a React Native View element?

Viewed 65

I've been working with RN using Views with styles added in the style tag, but yesterday I found out that I could add the same style but as a property, for example:

<View style={{marginTop: 20}} />

is the same as:

<View marginTop={20} />

I don't know why the docs didn't say anything about it.

Is it deprecated?

Thanks

3 Answers

This actually works? I just checked the typescript definitions and margin is not listed as a property for View.

If you read the docs for View though it says View should be used with Stylesheet.

enter image description here

As for if this is deprecated... I'm not sure. Sounds like you found some loop hole if adding styles directly to the component actually works.

It's not deprecated. You can read more about layout-props here: https://reactnative.dev/docs/layout-props#margintop

For more complicated styling of a component, I would always prefer "style" but it could make sense to use if you have a number of almost similar components where only one or a few style-properties are different. E.g. with a list of cards in different colours. You can have the general style in the "style"-prop and then set the unique color in a "background-color"-prop.

View component have a style prop in which we can pass our styleSheet custom object. View don't have style properties as a prop.

We can only pass the prop to the child component.

Related