Insert a style tag in a React component

avatar

Borislav Hadzhiev

Last updated: Apr 19, 2022

banner

Photo from Unsplash

Insert a style tag in a React component #

To insert a style tag in a React component, wrap your css in a template string in the style tag. The expression between the curly braces will get evaluated and the styles will get added.

App.js
const App = () => { const styles = ` .my-h2 { padding: 25px; background-color: salmon; color: white; } `; return ( <div> <h2 className="my-h2">Hello world</h2> <style>{styles}</style> </div> ); }; export default App;

The expression between the curly braces in the style tag will get evaluated and the styles will get added.

react insert style tag

You can also inline the css directly in the style tag.

App.js
const App = () => { return ( <div> <h2 className="my-h2">Hello world</h2> <style>{` .my-h2 { padding: 25px; background-color: salmon; color: white; } `}</style> </div> ); }; export default App;

The code snippet above achieves the same result.

Note that the styles we added with the style tag are not scoped to the App component.

Another component can use the my-h2 class as long as the App component is rendered.

An alternative approach is to use a file with a .css extension and write and import your global css files.

Here is how we would move our css into a file called App.css.

App.css
.my-h2 { padding: 25px; background-color: salmon; color: white; }

And here is how we would import the css file into our App.js file.

App.js
import './App.css'; const App = () => { return ( <div> <h2 className="my-h2">Hello world</h2> </div> ); }; export default App;

This is the more commonly used approach for writing and applying css to React components.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.