Styling in ReactJS

When we work on UI part of our application, we need to do a lot of styling for it to look good and easy to navigate.

We generally use CSS for this purpose. But sometimes it very tedious and time consuming for a big application.

For ReactJS, we can use Semantic.

  • Semantic UI: It is a development framework that helps create beautiful, responsive layouts using human-friendly HTML.
  • Semantic UI React: Semantic UI React is the official React integration for Semantic UI.

Semantic UI

This is a CSS file and can be used in any HTML file. We can just include a CDN in the header of the file.

Semantic UI usage

Below are the steps on how we can use Semantic UI in our ReactJS application.

  • First we need to get the CDN link. A CDN (Content Delivery Network) refers to a geographically distributed group of servers which work together to provide delivery of Internet content like HTML pages, javascript files, stylesheets, images etc.
  • Below is the CDN link for Semantic UI that I will be using in my examples
https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css
  • Include this file in index.html of your application under Heading tag.

Now you can use the CSS classes where ever you want in your application.
You can find a lot of information about Semantic UI classes in the Semantic UI site.

  • Click on any element that you want to create on the left hand menu.
  • You can see its details and the various types of that element.
  • By clicking on <> across a type, you can see the code and related CSS classes for that element.
  • You can copy the code from here as well or use the classes the way you want in your code.

Below is a sample code for creating Breadcrumb in you application using Semantic UI

import React from 'react';
import ReactDOM from 'react-dom';

const App = function () {
    return (
        <div class="ui breadcrumb">
            <a class="section">Home</a>
            <div class="divider"> / </div>  
            <a class="section" href="https://tutorials4sharepoint.wordpress.com/">Women Clothing</a>
            <div class="divider"> / </div>
            <div class="active section">Wedding Wears</div>
        </div>
    );
};

ReactDOM.render(<App />, document.getElementById('root'));

Below is the output of above code

Semantic UI React

Semantic UI React is the official React integration of Semantic UI. It is a JavaScript file. We can install it using NodeJS Command prompt. Below is the CDN link for this as well.

https://cdnjs.cloudflare.com/ajax/libs/semantic-ui-react/0.84.0/semantic-ui-react.min.js

Select the element that you want to include your application from Semantic UI React site. You can see the code and use it in your application.

I will be installing the JavaScript file first.

npm install --save semantic-ui-react

Use Shift + Alt + F to format the code in Visual Studio Code.
Now, you can simply import the element you want to use, using import statement.

Below is a sample code on how can you use a Breadcrumb using Semantic UI React

import React from 'react';
import ReactDOM from 'react-dom';
import { Breadcrumb } from 'semantic-ui-react';

const App = function () {
    return (
        <div>
            <Breadcrumb>
                <Breadcrumb.Section link>Home</Breadcrumb.Section>
                <Breadcrumb.Divider />
                <Breadcrumb.Section link><a href="https://tutorials4sharepoint.wordpress.com/">Women Clothing</a></Breadcrumb.Section>
                <Breadcrumb.Divider />
                <Breadcrumb.Section active>Wedding Wears</Breadcrumb.Section>
            </Breadcrumb>
        </div>
    );
};

ReactDOM.render(<App />, document.getElementById('root'));

Below is the output of above code

If you click on Women Clothing, you will be navigated to a link (for sample, I have used my site as the link).

Refer JS variable or function in JSX in ReactJS

When we write our code, we sometimes want to keep some text dynamic rather than static. For example, text of a button or label.

Below is an example to show how to use a JavaScript variable in JSX code. We simply place the JavaScript variable inside curly braces {}.

// Import the React and ReactDOM libraries
import React from 'react';
import ReactDOM from 'react-dom';

// defining a javascript function
function getButtonText(){
    return "Text from function";
}

// Create a React component. This is a function based component.
const App = function() {
    var btnTxt = "Submit";
    return (
<div>
            <label class="label" htmlFor="emailId">Enter Email: </label>
            <input id="emailId" type="text" />
            <button style= {{backgroundColor:"red", color:"white"}}> {btnTxt} </button>
            <button style= {{backgroundColor:"blue", color:"white"}}> {getButtonText()} </button> 
        </div>
    );
};

// Take the React component and display it on the screen. 
// There is div element with id='root' present in index.html in public folder.
ReactDOM.render(
    <App />,
    document.getElementById('root')
);

You can use any type of variable like number, array etc, but you cannot use object.

const btnTxt = 123456;
const btnTxt = "7576hjgj";
const btnTxt = ['Hi','Hello']; //Text displayed on button will be "HiHello"
const btnTxt = ['Hi',1234]; //Text displayed on button will be "Hi1234"
const btnTxt = [100,200]; //Text displayed on button will be "100200"
const btnTxt = {text:"Click Me!"}; //This piece of code will give error as it will not accept code
If you want to use this, you need to make changes to the JSX code. 
<button>btnTxt.text</button>

You will get bellow error if you use JavaScript Object variable in JSX

Other related articles

Introduction to ReactJS
ReactJS Environment Setup
Introduction to JSX
Styling in JSX

Styling in JSX in ReactJS

Let’s see how to do the styling of HTML elements in JSX.

Below is a code in HTML with styling



<div>
   <label class="label">Enter Email: </label>
   <input id="emailId" type="text" />
   <button style="background-color: red; color: white;>Subscribe</button>
</div>


If you insert above HTML code in your React application, you will get error like the below one

Let’s convert the styling as per JSX styling standards
Below is the converted code in JXS



<div>
    <label className="label">Enter Email: </label>
    <input id="emailId" type="text" />
    <button style= {{backgroundColor:'red', color:'white'}}>Subscribe</button>
</div>


Here we can see the difference between two statements

<button style="background-color: red; color: white;">Subscribe</button>
<button style= {{backgroundColor:'red', color:'white'}}>Subscribe</button>

Below is the difference:

  • double quotes (“) at the starting and end are replaced by curly braces ({}).
  • We do not use semicolons(;) to separate and end the properties. We just use comma(,) to separate the properties.
  • The value of properties are enclosed in single quotes(‘) OR double quotes(“) to make them string.
  • If there is any property name like background-color, hyphen(-) is removed and the property is renamed as per CamelCase standards, like backgroundColor.
  • To indicate a CSS class for any element in JSX, we use className instead of class. We already use class keyword to define a class in our JavaScript code.

If you use this code, and write this code in index.js file. htmlFor is used so that we can map label tag with input tag

// Import the React and ReactDOM libraries
import React from 'react';
import ReactDOM from 'react-dom';

// Create a React component. This is a function based component.
const App = function() {
    return (      
<div>
            <label className="label">Enter Email: </label>
            <input id="emailId" type="text" />
            <button style= {{backgroundColor:'red', color:'white'}}>Subscribe</button>
        </div>
    );
};

// Take the React component and display it on the screen. 
// There is div element with id='root' present in index.html in public folder.
ReactDOM.render(
    <App />,
    document.getElementById('root')
);

the error message will not be displayed anymore and you will see the below output.

If you click on Enter Email, focus is moved to the textbox.

Introduction to JSX in ReactJS

Before going through this article, kindly first read below articles:

  • JSX is also known as JavaScript Syntax Extension which is an extension to the syntax of JavaScript.
  • Browsers don’t understand JSX code. We first write JSX then run tools like Babel to turn it into normal JavaScript.
  • It is faster as it performs optimization while compiling the code to JavaScript and most of the error are caught during compilation.
  • It looks like HTML and can be placed in JavaScript code.
  • It determines the content of the React app just like normal HTML.
  • Styling in JSX is a little different than HTML.
  • Below is a sample JSX code
const App = function() {
    return <div>Hello World!</div>;
};

This looks a lot like HTML code, but is a JSX code.
Let’s see why use of JSX is recommended in React.

  • Open Babel home page.
  • Click on Try it out option on top of the page.
  • Paste your JSX code on left side, you will see the converted code on the right side.
  • You can see that JSX code is much easy to write, understand and manage.

Sample Program in ReactJS

Let’s continue with our previous article: ReactJS Environment Setup where we have created a ReactJS application which has the default code, how to start and stop it, and various files that exist in the application.

Let’s change the default code in the application and write our own code to create an application. Start the application and do not close it. Whatever change you make in the code, once you save it, it will automatically gets reflected in the browser.

Follow the below steps:

  • Delete all the files in src folder.
  • Create a new file in src folder: index.js. The browser will display nothing as there is no code to display.
  • Write the following code in index.js file. import the necessary libraries or other dependencies.
// Import the React and ReactDOM libraries
import React from 'react';
import ReactDOM from 'react-dom';

// Create a React component. This is a function based component.
const App = function() {
    return <div>Hello World!</div>;
};

// Take the React component and display it on the screen. 
// There is div element with id='root' present in index.html in public folder.
ReactDOM.render(
    <App />,
    document.getElementById('root')
);

Below is the output of above code

import in ReactJS

Before performing the import, we need to install the library using npm. Most of them are already installed while installing create-react-app.

You will find these libraries or dependency files in node_modules folder of your application. You can import any file or dependency that is available in this folder in your code. You can also install more files in this folder.

Here, we have explained the import statement in ReactJS code. Below is an import statement to import react library.

import React from 'react';
  • import: We use this if we want to get the code from some other file or dependency.
  • React: This is a variable name we want to assign this import to.
  • from: We are about to specify the name of the library or file we are importing from.
  • ‘react’: The name of the dependency or path to the file we are importing.

Below are other import statements that we will be using across various applications

import ReactDOM from 'react-dom';
Other related articles

Error: localhost:3000 doesn’t work

There can be a case when you start your application, localhost:3000 will open in browser but nothing is displayed.

The workaround for this is go back to NodeJS Command prompt.

Copy http://192.168.220.1:3000/ (this can be different on your machine) and paste it in on browser.

You will be able to see the content of your application in the browser.

Error: Something is already running on port

Sometimes we can get a message “Something is already running on port”

To resolve this error, you can either

  • Close the application that is running on the specified port and start this application again.
  • Type Y and start this application on another port.
  • Type N to exit the process. In this case, application will not be started.

Introduction to ReactJS

  • ReactJS is a front-end library developed by Facebook.
  • It handles the View layer of web and mobile applications.
  • We can also create reusable UI components.
  • ReactJS is used to show content (HTML) to users and handle user interaction.
  • ReactJS is a declarative, efficient, and flexible JavaScript library for building user interfaces.
  • Components in React
    • It lets you compose complex UIs from small and isolated pieces of code called components.
    • Everything in ReactJS is components. It helps in maintaining the large code.
    • A component is a function or class that produces HTML to show the user (using JSX) and handles feedback from the user (using Event Handlers).
    • React components are made using JavaScript functions or classes.
  • React can work by itself, but it can also work with other libraries, packages, databases and servers.
  • JSX (JavaScript Syntax Extension) is recommended to be used with ReactJS.
  • ReactJS implements one-way data flow using Flux.
  • ReactJS uses JavaScript virtual DOM to improve the performance of ReactJS apps.
  • We can use ReactJS with both client side and server side.
  • ReactJS covers only the view part of your app. You need to choose other technologies for the logical part of your app.
  • Before moving forward, let us setup the environment to develop ReactJS Apps. You can use any editor to create the apps. I will be using Visual Studio Code.
  • React is separated into two libraries
    • React knows what a component is and how to make components work together.
    • ReactDOM knows how to take a component and make it show up in the DOM.
  • We can use CDN links for React and ReactDOM for our application.
Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started