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

8 3

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay