Why do style props work as component props in React Native's View?

Viewed 117

By mistake, I have ended up spreading a style object as component props, instead of passing it as a style={{ ... }} prop. I didn't catch the mistake until later on, beacuse it worked.

<View flex={1} margin={30} borderWidth={2} />

will render the same as:

<View style={{ flex: 1, margin: 30, borderWidth: 2}} />

also, mixing these props with the style prop works as expected (that is, if you expected it to work in first place). The following Views all render the same:


<View
    borderWidth={5}
    style={{ flex: 1, margin: 30, borderWidth: 2}}
    backgroundColor="red"
/>

<View style={{
    ...({ borderWidth: 5 }),
    ...({ flex: 1, margin: 30, borderWidth: 2 }}),
    ...({ backgroundColor: "red" })
}} />

<View style={[
    { borderWidth: 5 },
    { flex: 1, margin: 30, borderWidth: 2 },
    { backgroundColor: "red" },
]} />

<View style={{
    borderWidth: 5,
    flex: 1, margin: 30, borderWidth: 2,
    backgroundColor: "red"
}} />

My question is, why - why does this work?

I tried searching for this in RN's docs, and on the web, but found nothing. To my knowledge, passing style props as component props should not work. Also, this may be considered a bug in the core RN project.

Does anyone have more info on this? Should I report to the devs?

p.s. I found this older SO thread from May 2020 about the same behavior, but the question is unanswered

p.p.s. I did not try yet, but this behavior may work with other core RN components

0 Answers
Related