QUICK RECAP

Chapter 1 provided an introduction to React, why it was created and its main purpose which is for building re-usable user interface elements. We also looked into other topics like JSX, the template-like engine that converts our components and other react code into Javascript and crucially enables us to directly add HTML elements into our Javascript code. We touched on a few of its rules and by extension React rules for example how a react component (or function) must return only one element. The Development Environment was also covered in Chapter 1, where we spoke about using CodeSandbox. This is not the only way to create React applications, you can create them locally on your system using create-react-app in any IDE (internal development environment) of your choice like Visual Studio Code. Components and Nested Components was also covered in Chapter 1, then we closed it off by building a Profile Page Application like Wikipedia pages.

In this Chapter we’d be looking at styling our react components further. There are three main ways of styling React components with CSS (Cascading Style Sheets):

  • Inline CSS
  • Object Reference
  • External CSS

INLINE CSS

As the name suggests, this involves styling the html elements directly. There is a tight coupling between the styles and the component’s functionality.

import React from "react";

const InlineStyle = () => {
 return <div style={{
  backgroundColor: "red",
  color: "black"
 }}>
  Inline CSS
 </div>
};

export default InlineStyle;

When using the inline style, you add two curly braces to the style attribute of the html element you want to style and use the camel case css attribute.

OBJECT REFERENCE

This involves styling our react components in the same file using objects. An example is shown below:

import React from "react";

const ObjectReference = () => {

 const styles = {
  backgroundColor: "red",
  color: "black"
 };
 
return <div style={styles}>
 Object Reference
</div>
};

export default ObjectReference;

The main takeaway in using Object Styling is that the keys in the object are all CSS style attributes but rather than using the CSS hyphenated naming style e.g. background-color, text-align; it uses the Javascript camel case naming style e.g. backgroundColor, textAlign. This is how you must name the object keys when using object reference styles.

Secondly, you would notice that in the style attribute added to the div element, we only used one curly brace unlike in the inline css sub-section above. You must recall that using two curly braces explicitly renders the Javascript code and since we already have an object with the proposed styles, this would lead to redundancy and spit out an error. Whenever, we use the Object Reference style, we only need one curly brace in the style attribute for the html element.

One of the main advantages of using Object Reference styling is that it is more elegant and enables you to separate your style from the components in the same file. In the process this leads to partial de-coupling of the style and functionality of your application.

EXTERNAL CSS

This involves creating an external css file and writing your styles in it. Firstly, this would make your application more modular, as you have separated the concerns of your application. Secondly, it would make the file where your functionality resides leaner leading to more readable and maintainable code. In the short run this may seem like an over-kill and for small, simple applications it is but in the medium/long-term, this is beneficial to both you and/or other members of the front-end team.

When using External CSS, you create a CSS file then define your attributes there, styling each UI element using any appropriate CSS selector; then you import the CSS file into where your main application file resides. We’d look more into External CSS in the next project HoverCSS.

TIP
To learn more about CSS Selectors, you can go here.

COLOR PALETTE LIBRARY – AwoCSS

Awo (pronounced as Aah-WOH) means color in Yoruba, one of the main tribes in Nigeria where I come from. This small library would involve creating a series of blocks that (for now) would contain colors that any designer or front-end developer can copy and use. The essence of this library is to create a series of color palettes that are unique to Africa e.g., from the fruits, food, flowers, animals etc that are unique and peculiar to African countries. The colors would be extracted from images of these items then named according to my discretion or from users’ suggestions. Below is the working code:

// Inline CSS - Color Library - AwoCSS (Aah-WOH)

import React from "react";

const Awo = () => {
    
    const showProperty = (tag) => {
        const element = document.querySelector(tag);
        const elementStyle = getComputedStyle(element).getPropertyValue("background-color");
        return alert(elementStyle);
    }
    
    return (
        <div>
            <h3 style={{
                marginLeft: "5%",
                marginTop: "2.5%"
            }}>AwoCSS</h3>
            <div className="red-div" style={{backgroundColor: "red", 
                            width: "100px",
                            height: "100px",
                            display: "inline-block",
                            marginLeft: "5%",
                            marginTop: "2.5%"}
                         } onClick={() => showProperty(".red-div")}></div>
                         
            <div className="yellow-div" style={{backgroundColor: "yellow", 
                            width: "100px",
                            height: "100px",
                            display: "inline-block",
                            marginLeft: "5%",
                            marginTop: "2.5%"}
                         } onClick={() => showProperty(".yellow-div")}></div>
                         
            <div className="green-div" style={{backgroundColor: "green", 
                            width: "100px",
                            height: "100px",
                            display: "inline-block",
                            marginLeft: "5%"}
                         } onClick={() => showProperty(".green-div")}></div>
                         
            <div className="blue-div" style={{backgroundColor: "blue", 
                            width: "100px",
                            height: "100px",
                            display: "inline-block",
                            marginLeft: "5%",
                            marginTop: "2.5%"}
                         } onClick={() => showProperty(".blue-div")}></div>
                         
            <div className="orange-div" style={{backgroundColor: "orange", 
                            width: "100px",
                            height: "100px",
                            display: "inline-block",
                            marginLeft: "5%"}
                         } onClick={() => showProperty(".orange-div")}></div>
                         
            <div className="indigo-div" style={{backgroundColor: "indigo", 
                            width: "100px",
                            height: "100px",
                            display: "inline-block",
                            marginLeft: "5%"}
                         } onClick={() => showProperty(".indigo-div")}></div>   
                            
            <div className="crimson-div" style={{backgroundColor: "crimson", 
                            width: "100px",
                            height: "100px",
                            display: "inline-block",
                            marginLeft: "5%",
                            marginTop: "2.5%"}
                         } onClick={() => showProperty(".crimson-div")}></div>
                         
            <div className="lightblue-div" style={{backgroundColor: "lightblue", 
                            width: "100px",
                            height: "100px",
                            display: "inline-block",
                            marginLeft: "5%"}
                         } onClick={() => showProperty(".lightblue-div")}></div>
                         
            <div className="chartreuse-div" style={{backgroundColor: "chartreuse", 
                            width: "100px",
                            height: "100px",
                            display: "inline-block",
                            marginLeft: "5%"}
                         } onClick={() => showProperty(".chartreuse-div")}></div>                      
        </div>
    );
}

export { Awo };

CODE EXPLANATION

Before I begin explaining the code above, I want to elaborate on exactly what I’m trying to do here. Its a simple series of steps.

  1. You click on boxes/palettes.
  2. An alert box shows on the screen with the rgb (red, green, blue) values of the palette.
  3. Then you copy that awo and use it for your project.

We have a component called Awo which returns various color palettes. In this component, we have one crucial function – showProperty(). This function uses Javascript to get the computed value of a CSS property. After this has been done, the next step is to devise a way to show this to the user/client. You can go about this in several ways, but I chose to simply alert the computed style/rgb values of the palette to the user. Since this is just a minimum viable product(mvp), this was the solution I felt was best; but you’re free to devise other ways of showing the palette values to the user.

The next blocks of code use the inline css to set the values of the various palettes (created as divs) and wrapping them all in a div-component as a value for the return statement of the Awo component. There’s a strange line of code that hasn’t been explained though and you’d see this line repeating itself:

onClick={() => showProperty(".red-div")}

What the above line is doing is using Javascript’s onclick function and calling the showProperty() function every time a palette is clicked. In the showProperty() function, we passed a parameter called “tag”, this selects each individual palette as this library would have lots of distinct colors then I just added the onclick function as an attribute of each individual div and passed the className selector as the tag.

Later in this series, we would talk about Hooks and find more reactive ways of handling this logic using useState() then with useReducer(). For now this would do.

And that’s a wrap for this project, below is a screenshot of the project, very soon I’d host the site live and put the link here. In the next section, we would be creating an Animation Library called HoverCSS. I love animation and can’t wait to discuss the project with you while talking about more React concepts.

Lare is an Applied Machine Learning Engineer. reactbyprojects is a journal of his journey towards mastering react while helping other people who might be interested in this technology. To view more of his Software Engineering projects, you can go to https://laresamdeola.com and for Machine Learning - https://machinelearning.com.ng. You can reach him via email lare@reactbyprojects.com or through his github https://github.com/laresamdeola

Related Article

0 Comments

Leave a Comment