Why, when, and how to use the style prop

The easiest way to style your components is using the style prop, where you get to passing a java script object that describes how you want your styling to look, and React then handles the rest, and passes that into the style prop of your dom attribute, right Kiwi?

While it's the easiest, I would say the style prop is also the least useful. It's great for when you have to do some one of styles or something like that, but it gets really unruly if you want to use it for styling everything. Now, it is true that in React native for example, the style prop is, outside of UI tool kit, it's pretty much the only thing you can use.

The style prop is something that comes with every basic dom element. [inaudible 00:00:38] have a style prop, H2s, paragraphs, so on, everything. One common approach to using it, is defining these styles objects. And so we have styles with the font family and a text line. We say, let's say color is red, all these things should turn red.

Here you can see kind of the limitations of the style prop. You need to be using java script objects, so font family, text line, are all using camel case, instead of the normal dash notation, and you have to pass in your values as strings.

The nice thing though, is you can pass in, java script expressions as well, random is bigger than point five, now every time this refreshes, the color is going to change. You can use everything from java script, so it's very very flexible, and if you're already used to java script and you have no idea about how CSX works, you're still not going to be able to use it, because you need to know what property names you can use. Where it becomes a little bit tricky is here we have lets say, a hello component, color black. You'll see that nothing happens, that's this component up here, so we have to manually pass in the style prop, and now this is going to turn black.

Another limitation of the style prop, is you have to manually pass it around, to make sure that it comes into all the components that you actually want it to use in. But it's really good for this sort of one of styling tricks. Something that you need to over ride with some java script where you have some other way to start a component, but you need to over ride a specific property, that's where the style prop comes in very handy. The way styles come into your HTML, every time you use your component, it's going to have this style prop with all of your styles copied in.

So that's the style prop, it's available by default, very flexible, and too far from normal CSX, I recommend using it when you have something very quick you have to hack together.

Know someone who wants to learn React and its whole ecosystem? Share πŸ‘‡


Cheers,
~Swizec