DEV Community

Cover image for The Beginner's Guide To React: Styling React Component with className and inline Styles
Bipin Rajbhar
Bipin Rajbhar

Posted on • Edited on

The Beginner's Guide To React: Styling React Component with className and inline Styles

Inline Styling

To style, a React element we need to pass an object instead of a string to the style attribute.

Note: The key of an object must in camelCase and the value is usually a string.

Example

<body> <div id="root">This will be replace by React</div> <script src="https://unpkg.com/react@16.13.1/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script> <script type="text/babel"> const rootElement = document.getElementById("root"); const style = { display: "inline-block", fontFamily: "sans-serif", margin: "24px", padding: "4px 8px", backgroundColor: "#1a202c", color: "white", borderRadius: "8px" }; const element = <h1 style={style}>DEV</h1>;  ReactDOM.render(element, rootElement); </script> </body> 
Enter fullscreen mode Exit fullscreen mode

Output

CSS Stylesheet

You can write your own CSS styles in a separate file, just save the file with the .css extension and add it to the head tag.

Note: But here we are using tailwindcss framework.

<body> <div id="root">This will be replace by React</div> <script src="https://unpkg.com/react@16.13.1/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script> <script type="text/babel"> const rootElement = document.getElementById("root"); const element = ( <h1 className="inline-block m-6 px-2 py-1 rounded-md font-bold text-white bg-gray-900"> DEV </h1>  ); ReactDOM.render(element, rootElement); </script> </body> 
Enter fullscreen mode Exit fullscreen mode

Output

Top comments (0)