Styling In React

Styling in React is a little different than usual. It’s core idea id to have our app visual pieces be self contained and reusable. That is why all of our HTML,CSS and JS all are in the same little black box we call component.

They way you specify styles in component is to define an object who properties are the same as we define the normal CSS properties and then assign the object to the JSX element by using the style attribute.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React from 'react';
import ReactDOM from 'react-dom';
class Superhero extends Component {
render() {
const Style = {
backgroundColor:this.props.color,
fontFamily:"Open Sans",
fontSize:90
}
return (
<div style={Style}>
{this.props.children}
</div>
);
}
}
ReactDOM.render(
<div>
<Superhero color='blue'>Superman</Superhero>
<Superhero color='green'>Hulk</Superhero>
<Superhero color='black'>Batman</Superhero>
<Superhero color='yellow'>Iron Man</Superhero>
<Superhero color='red'>Flash</Superhero>
</div>,
document.getElementById('root')
);

Single word CSS properties(like padding, margin, color) remains unchanged and Multi word CSS properties(like font-family, font-style, background-color) are turned into camel case words with the dash - removed. As you can see above we didn’t use the px suffix in our style property. React allows us to omit the px suffix for a bunch of CSS properties.

Now if you preview this in the browser this will output as:

stylingreact

Pretty Cool Right!!!

React Gotcha:

If you need to specify a Vendor-prefixed version of a CSS property instead of first letter being camelCase like this webkitFilter, the first letter is actually capitalized like this WebkitFilter
We can even specify a separate background color for each of our Superhero’s.

For further information checkout the docs

fin!

Proudly powered by Hexo and Theme by Hacker
© 2017 Mohit Garg