
Inline CSS in React
19 January, 2023
0
0
0
Contributors
Introduction
Inline CSS is the styling methodology wherein we write CSS inside of the JSX in the component. We write the style in the form of a JavaScript object. The kebab-cased style names are converted into camel-case to be accepted as valid JavaScript keys. This functionality is supported by React by default and we do not need any library to be installed in order to write inline CSS.
Example of inline CSS
Here are some examples of using inline CSS in a React component:
import React from 'react';
function MyButton() {
return (
<button
style={{
backgroundColor: 'blue',
color: 'white',
fontSize: '16px',
padding: '10px 20px'
}}
>
Click me!
</button>
);
}
In this example, the button component has several inline styles applied to it. The style
prop takes an object where the keys are the camelCased versions of the CSS properties and the values are the property values.
Generate styles based on props
You can also use JavaScript expressions to generate the values of the styles:
import React from 'react';
function MyButton(props) {
const size = props.large ? '20px' : '16px';
return (
<button
style={{
backgroundColor: 'blue',
color: 'white',
fontSize: size,
padding: '10px 20px'
}}
>
Click me!
</button>
);
}
In this example, the fontSize
of the button is determined by the large
prop. If large
is true
, the fontSize
will be 20px
, otherwise it will be 16px
.
Using the emotion
library
While that is pretty exhaustive in what it can achieve, we can also get the same results by using the emotion
library. The benefit is that we need not move to camelCase style keys because we write the styles inside of a string literal block.
import React from 'react';
import { css } from 'emotion';
function MyButton() {
return (
<button
className={css`
background-color: blue;
color: white;
font-size: 16px;
padding: 10px 20px;
`}
>
Click me!
</button>
);
}
In this example, the css
function generates an object containing the inline styles. The object is passed to the className
prop, which applies the styles to the element.
Inline CSS is one of the most basic ways to write CSS but let us learn about some of the more advanced methods in the next shows.