React - Using CSS for Styling Components

Hi There!

As we know of components, states and props already, lets now look are UI by applying CSS.

In react, we can have common CSS created across the application or every component can have its own CSS defined.

Similar to any SPA, We can apply CSS in 2 ways:

  • Using external .css files
  • Using Inline CSS

Using external CSS file

  • You can have one single CSS file for entire react app. But it is recommended to use that file for basic or generic styling covering elements which will be seen throughout the app lifecycle such as navbar, headers, footers etc.
  • Every component can include its own CSS file.
  • Unlike .js or .jsx file, we need to make sure we are including the .css extension while. importing in any component.
  • As react uses JSX, we cannot use class property of HTML, instead we need to use className property.

  • Example

    • my-app.css

    •   .book {
          background-color: rgb(212, 201, 201);
          border-radius: 1rem;
          padding: 1rem 2rem;
          max-width: 300px;
          max-height: auto;
        }

        .book h1 {
          margin-top: 0.5rem;
        }

        .book h4 {
          margin-top: 0.25rem;
        }

        .book p {
          margin-top: 0.5rem;
        }

    • book.css

    •   .book {
          align-content: center;
          text-align: center;
        }

        .btn {
          font-weight: bold;
          background-color: orange;
          border-radius: 10px 10px;
        }

    • Index.js
    • import ReactDOM from "react-dom";
        import "./css/my-app.css";
        import "./css/book.css";

        //Children 1
        class BookImage extends React.Component {
          render() {
            const coverImage = this.props.coverImage;

            return (
              <img
                src={coverImage}
                alt="Book Cover"
                style={{ maxHeight: 300, maxWidth: 300 }} //inline style
              ></img>
            );
          }
        }

        //children 2
        class BookAuthor extends React.Component {
          render() {
            const { title, author } = this.props;
            return (
              <>
                <section>
                  <h1 className="book-title">{title}</h1>
                  <h4 className="bok-author">{author}</h4>
                  <p className="description">{this.props.description}</p>
                  <button className="btn" onClick={this.props.buyBook}>
                    Buy this Book!
                  </button>
                </section>
              </>
            );
          }
        }

        //Parent component
        class Book extends React.Component {
          render() {
            const title = {
              title: "The Alchemist",
            };
            const writer = {
              author: "Paulo Coelho",
            };
            const description = {
              description: "Lorem, ipsum dolor sit amet adipisicing.",
            };

            //method to buy the book, to be passed to childrens who needs it
            const buyBook = () => {
              alert("Bought it!");
            };

            return (
              <>
                {/*  */}
                <article className="book">
                  <BookImage coverImage="./images/the-alchemist.jpg" />

                  <BookAuthor
                    {...writer}
                    props={title}
                    description={description.description}
                    buyBook={buyBook}
                  ></BookAuthor>
                </article>
              </>
            );
          }
        }

        ReactDOM.render(<Book />, document.getElementById("container"));

    • Result

















Inline CSS

  • As you must have noticed in the earlier example, using inline CSS is different than how we usually do in JavaScript applications or HTML templates.
  • As we are working in JSX, while applying inline styling (CSS), we need to inform react about that. 
  • As we know, curly brackets is a way by using which we can switch from JSX to JavaScript in the JSX code.
  • React also understands HTML style property, but while using in JSX, it expects style objects unlike strings, which can be passed as a JavaScript objects.

  • React automatically adds px suffix to these values while rendering.

  •   style={{ maxHeight: 300, maxWidth: 300 }}
     

    • We have used 2 curly brackets in above example:
      • First curly bracket is to enter in the JavaScript world so react understands it.
      • Second is to set the style object.

      • Style objects are JavaScript objects with standard CSS attributes and corresponding values.

      • Property name should be without quotes (maxHeight) but value should be string or numbers.

      • All CSS property names follow camel-casing.




Comments

Popular Posts