WebVeta - Advanced, unified, consistent search for your website(s), from content of your website(s), blogs(s). First 50 customers, who sign-up prior to 15/05/2024 get unlimited access to existing features, newer features for at least 1 year. Sign up now! https://webveta.alightservices.com/
Categories
Javascript React

React Functional Components, showing or hiding content based on conditions

In React Functional components, content can be shown or hidden based on conditions.

function Component1 {
    return (
        <React.Fragment>
            <p>Hello!</p>
        </React.Fragment>
    );
}

The above component would always show the paragraph with the text “Hello!”. Now, let’s say if we are displaying content conditionally, we can use the following syntax:

function Component1 {
    const [condition, setCondition] = React.useState(false);

    return (
        <React.Fragment>
            {condition && (
                <React.Fragment>
                    <p>Condition is true!</p>
                </React.Fragment>
            )}
            {!condition && (
                <React.Fragment>
                    <p>Condition is false!</p>
                </React.Fragment>
            )}
            <p>Hello!</p>
        </React.Fragment>
    );
}

In the above code snippet, we have created a state variable condition and initialized to false. If condition is true, the paragraph with text – “Condition is true!” would be displayed. If condition is false, the paragraph with text – “Condition is false!” would be displayed. Irrespective of the value of condition, the paragraph with the text – “Hello!” would be displayed.

Based upon the application, the value of condition can be changed and the application’s user interface would be updated appropriately.

setCondition(true);

The above coding pattern can be used for example for displaying a “Please wait” message while some data is loading. Or showing a table only when there is data, else showing something like “No data!”

React can be progressively integrated into existing websites or for new websites, very easy learning curve and can be run from browser without even having the node based server-side rendering. Of course, node based server-side rendering etc… can be done like other SPA frameworks.

The production version of React in-browser scripts are ~132kb and about ~45.1kb compressed and can be used from CDNs. The custom JSX code can be transpiled before production deployment for slightly faster performance without using babel in browser.

This would be the content of a future post. In the post, I would discuss about transpiling and minifying.

Compressing and serving with gzip / brotli or even using your own CDN’s in the cloud is an entirely different topic, but can be done easily for static content.

I don’t have any fake aliases, nor any virtual aliases like some of the the psycho spy R&AW traitors of India. NOT associated – “ass”, eass, female “es”, “eka”, “ok”, “okay”, “is”, “erra”, yerra, karan, kamalakar, diwakar, kareem, karan, sowmya, zinnabathuni, bojja srinivas (was a friend and batchmate 1998 – 2002), mukesh golla (was a friend and classmate 1998 – 2002), thota veera, uttam’s, bandhavi’s, bhattaru’s, thota’s, bojja’s, bhattaru’s or Arumilli srinivas or Arumilli uttam (may be they are part of a different Arumilli family – not my family).

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
React

React state management in functional components

In React, functional components can use state by using useState(). Let’s look at a code example:

const [mode, setMode] = React.useState(0);

In the above code block we are destructuring the return value of useState. mode is a read-only constant, that can be read and used. For changing the value the setMode can be used.

The usual naming convention is the constant name for the first object and setVariableName for the function, but the function name can be anything.

The following code example demonstrates accessing the variable and updating the variable.

{{mode}}

setMode(1);

But any attempts to modify the value of the constant would result in an error.

I don’t have any fake aliases, nor any virtual aliases like some of the the psycho spy R&AW traitors of India. NOT associated – “ass”, eass, female “es”, “eka”, “ok”, “okay”, “is”, “erra”, yerra, karan, kamalakar, diwakar, kareem, karan, sowmya, zinnabathuni, bojja srinivas (was a friend and batchmate 1998 – 2002), mukesh golla (was a friend and classmate 1998 – 2002), thota veera, uttam’s, bandhavi’s, bhattaru’s, thota’s, bojja’s, bhattaru’s or Arumilli srinivas or Arumilli uttam (may be they are part of a different Arumilli family – not my family).

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
React

React Fetch API

React Fetch API is used for calling REST API’s.

First some sample code and then a lengthy discussion of various options.

const postRequestOptions = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: {}
};

postRequestOptions.body = JSON.stringify(jsonObject);

fetch('/path', postRequestOptions)
.then(response => {console.log(response); return response.json();})
.then(data => console.log(data);

In the above code block we have declared a postRequestOptions object, for POST HTTP method, declared the content type as application/json.

Then we set the body of the postRequestOptions object by representing a json object as a string.

Then we used the fetch API, once the response is returned, we are logging the response, creating a data object from the received response’s json and logging the object to the console.

There are several options for the RequestOptions:

referrer: The referrer can be set

referrer policy: Tells the browser to set the referrer header based on the policy. “strict-origin-when-cross-origin”, “no-referrer-when-downgrade”, “no-referrer”, “origin”, “origin-when-cross-origin”, “same-origin”, “strict-origin”, “unsafe-url”.

mode: “cors”, “same-origin”, “no-cors”

credentials: Whether to send cookies and tokens. “same-origin” – default, “include”, “omit”

cache: “default”, “no-store”, “reload”, “no-cache”, “force-cache”, “only-if-cached”

redirect: “follow” – error, “error”, “manual”. If you want error to be raised for 302, instead of sending another request use “error” or you can know the status by accessing the response.status that provides the HTTP status code.

integrity: SHA256/384/512 of expected hash.

keepalive: true or false, used when you want to do something on window.onunload()

Here is a webpage with a very detailed discussion of the options:

https://javascript.info/fetch-api

Categories
HTML Javascript React

Basic introduction to using React in-browser

React is a SPA library built by Facebook and has very wide usage. Angular and Vue offer similar functionality. The three frameworks have their own advantages and disadvantages which is out of scope.

For quick prototyping and for other reasons, there might sometimes be a need for using React in-browser i.e include some Javascript files from CDN, write some Javascript and see these in usage.

In this blog post, I won’t go into great lengths or details, but more of a getting started blog post.

I am assuming you would like to use JSX syntax and would like babel to transpile in-browser.

Include the following 3 javascript files:

<script crossorigin src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Note: Assuming you are developing quick prototype, I have provided the development version links for React 17.0.2. But there are minimized production versions. The development scripts are useful for easier debugging because of detailed error messages.

Now include another .js file of your choice and include the js file in your HTML page – assuming the .js file has a name of RootComponent.js

<script src="~/js/RootComponent.js" type="text/babel"></script>

Note the type is “text/babel” because we would be using JSX for our markup.

Add a div with a id of “root” in your HTML page which would become the container for our React application. I have added Please wait… because the browser would display Please wait… while React framework initializes.

<div id="root">Please wait...</div>

Now add the following code snippet to your RootComponent.js

const rootElement = document.getElementById('root');

function App() {
    return (
        <div>Hello World!</div>
    )
}

ReactDOM.render(
    <App />,
    rootElement
)

In the above few lines of code, we have used plain javascript for getting the div with an id of “root”.

We have defined a minimal functional component by the name of App.

We are using React library and calling a method called Render and asking React library to render the App component in the place of the root element i.e the div with the id of “root”.

I don’t have any fake aliases, nor any virtual aliases like some of the the psycho spy R&AW traitors of India. NOT associated – “ass”, eass, female “es”, “eka”, “ok”, “okay”, “is”, “erra”, yerra, karan, kamalakar, diwakar, kareem, karan, sowmya, zinnabathuni, bojja srinivas (was a friend and batchmate 1998 – 2002), mukesh golla (was a friend and classmate 1998 – 2002), thota veera, uttam’s, bandhavi’s, bhattaru’s, thota’s, bojja’s, bhattaru’s or Arumilli srinivas or Arumilli uttam (may be they are part of a different Arumilli family – not my family).

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.