Know Version of ReactJS

Create a new react application. Delete all the files from src folder except index.js. Replace the code with the following code

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

class App extends React.Component {
    render(){
        return(
          <div>React version: {React.version}</div>
        );
    }
}

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

Below is the output of above code.

Output is subject to change as per the ReactJS version you are using.

setState() for State in ReactJS

      • We have seen what exactly a State is in ReactJS, how to initialize state data and update it.
      • setState() causes a component to re-render.
      • Before moving further, be aware of this that setState() function in ReactJS works in ASYNCHRONOUS fashion. That is, when we update state values, they are not immediately available for use.
      • Do not modify state directly, Use setState()
    this.state.value='Text'; is wrong. You can only use this in constructor
    this.setState({value: 'Text'}); is right
    • In this article, we will see ways to update state data.
    • There are two ways to update state data
      • Object based
      • Function based: We use Arrow Functions for this approch
index.js

Create a new application. Delete all files from src folder except index.js.
Below is the code that demonstrate both the approaches. Replace the code in index.js file with the below code.

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

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = { 
            funstr: 'Functional Original text!' , 
            objstr: 'ObjectBased Original String' 
        };
    }

    clickMeFA = () => {
        console.log('Functional based approach');
        console.log(this.state.funstr);
        this.setState(() => ({ 
            funstr: 'Functional Updated Text' 
            }),() => {
                console.log(this.state.funstr);
            });
    }

    clickMeOBA = () => {
        console.log('Object based approach');
        console.log(this.state.objstr);
        this.setState({ objstr: 'ObjectBased Updated Text' });
        console.log(this.state.objstr);
    }

    render() {
        return (
            <div>
                <button onClick={this.clickMeOBA}>Click Me     Objectbased</button>
                <button onClick={this.clickMeFA}>Click Me FuncBased</button>
            </div>
        );
    }
}

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

Below is the output of above code

Related Article

Event Handling in ReactJS: This article have another example related to setState()

Rendering content conditionally in ReactJS

In State in ReactJS, we have seen how to fetch the data in State object for the Component. But we have not seen how to display error message if latitude and longitude are not available.

Copy and paste below code in index.js file.

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

class App extends React.Component {
    constructor(props) {
        // super() is used to call the constructor os 
        super(props);

        // this is the only time we use direct assignment to state, 
        // that is at the initialization time
        this.state = { lat: null, long: null, errMsg:'' };

        window.navigator.geolocation.getCurrentPosition(
            position => {
                // update state data using setState() method
                this.setState({ lat: position.coords.latitude, long: position.coords.longitude });
            },
            err => {
                this.setState({ errMsg: err.message });
            }
        );
    }
    render() {
        // When Latitude and longitude is not fetched, we will show an error message
        if(this.state.errMsg && !this.state.long){
            return <div><b>Error: </b>{this.state.errMsg}</div>
        }

        // When we know Latitude and Longitude, then their values will be displayed
        if(!this.state.errMsg && this.state.long){
            return(
                <div>
                    <b>Latitude: </b>{this.state.lat}<br />
                    <b>Longitude: </b>{this.state.long}
                </div>
            );
        }

        // When the values are still loading
        if(!this.state.errMsg && !this.state.long){
            return<div>Loading...</div>
        }
    }
}

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

The output will be based on data fetched.

State in ReactJS

  • State is a JavaScript object that contains data for a component.
  • We can use State only in Class Components. We can use them in Functional Components by using hooks system.
  • State and props are two different things, so do not get confused between the two.
  • When we update State, the component is almost instantly rendered.
  • We should initialize State when the component is created.
  • State can ONLY be updated using the setState function.
Initialize State when the component is created
  • We use constructor() function to initialize the State.
  • This constructor() function is not related to ReactJS but is a JavaScript concept.
  • We define constructor() inside the class.
  • Whenever we create an instance of component, constructor() function is automatically and instantly called before anything else. Hence, this is the best way to initialize the State.
  • When we define constructor(), it automatically calls props object. This is the same props that we discussed earlier in Functional Component.
  • super()
    • Before doing anything else inside constructor(), we have to call a function super() and pass props in it.
    • We can see that our class extends functionality from React.Component base class. This base class has a constructor function that has the code for the component.
    • The constructor() that we define in our class will override the constructor of the base class. To make sure that the base class’ constructor() code still gets called, we use super(props).
    • If we do not call super(), we will get an error message “super() hasn’t been called“.
    • super() should be the first statement in the constructor().
index.js

Below is a code to demonstrate the State by getting Longitude and Latitude of your current location. We will be using only one file in src folder: index.js. Place the below code in index.js file.

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

class App extends React.Component {
    constructor(props) {
        // super() is used to call the constructor of parent class
        super(props);

        // this is the only time we use direct assignment to state, 
        // that is at the initialization time
        // we use null if we expect the value is either numerical or decimal
        this.state = { lat: null, long: null };

        window.navigator.geolocation.getCurrentPosition(
            position => {
                // update state data using setState() method
                this.setState({ lat: position.coords.latitude, long: position.coords.longitude });
            },
            err => console.log(err)
        );
    }
    render() {
        return (
            // this is how we use state data in our code            
            <div>
                <b>Latitude:</b> {this.state.lat}
                <b>Longitude:</b> {this.state.long}
            </div>
        );
    }
}

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

Below is the output of above code. It will change as per your location. Please note that you have to enable your location sharing for this example to work.

Class in ReactJS

  • Components are categorized in two types
    • Functional Components
    • Class-based Components
  • In previous article, we have seen only Functional Components. In this article, we will learn about Class-based components.
  • Class Components must be a JavaScript class
  • The Class should extend React.Component
  • Must define a render method that returns some amount of JSX

Let’s see how to create a class and display it on the page.

  • We will create a new app named classdemo
  • Take the reference from Environment Setup – ReactJS article
  • Delete all the files from src folder and create two new files in it: index.js and Comments.js. As of now, I am displaying the static values.
Comments.js

Paste the below code in this file

import React from 'react';
import { Comment } from 'semantic-ui-react';

class Comments extends React.Component {
    render() {
        return (
            <Comment>
                <Comment.Content>
                    <Comment.Author as='a'>Akanksha</Comment.Author>
                    <Comment.Metadata>                  
                        <div>Today</div>
                    </Comment.Metadata>
                    <Comment.Text>Nice Post!!</Comment.Text>
                    <Comment.Actions>
                        <Comment.Action>Reply</Comment.Action>
                    </Comment.Actions>
                </Comment.Content>
            </Comment>
        );
    }
}

export default Comments;
index.js

Paste the below code in this file

import React from 'react';
import ReactDOM from 'react-dom';
import { Comment } from 'semantic-ui-react';
import Comments from './Comments';

class App extends React.Component {
    render() {
       return (
        <Comment.Group>
             <Comments />
        </Comment.Group>
       );
    }
 }

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

Start the app from NodeJS Command Prompt.
Below is how the above application looks

Nesting custom component within another custom component in ReactJS

Till Props in ReactJS we have seen parent-child components and passing values from parent component to child component.

In this article, we will be learning how to insert one custom component withing another custom component. Lets continue with the example we created in Props article.

Let’s create something like

In above image, you can see that we have inserted the Comments within a Card, with two Buttons: Approve and Reject. The reference for the code is taken from Semantic UI React site.

ApprovalCard.js

Let us create a new file ApprovalCard.js in src folder. Paste the below code in it.

import React from 'react';
import { Card, Button } from 'semantic-ui-react';
import Comments from './Comments';

const ApprovalCard = function (props) {
    return (
        <Card>
            <Card.Content>                
                <div>{props.children}</div>
            </Card.Content>
            <Card.Content extra>             
                <div className='ui two buttons'>
                    <Button basic color='green'>
                        Approve
                    </Button>
                    <Button basic color='red'>
                        Decline
                    </Button>
                </div>
            </Card.Content>
        </Card>
    );
}

export default ApprovalCard;
Comments.js

We are not changing the code in this file. Below is the code for this file just for your reference.

import React from 'react';
import { Comment} from 'semantic-ui-react';
import faker from 'faker';

const Comments = function (props) {
    return (
            <Comment>
                <Comment.Avatar src={faker.image.avatar()} />
                <Comment.Content>
                    <Comment.Author as='a'>{props.user}          </Comment.Author>
                    <Comment.Metadata>                        
                        <div>{props.time}</div>
                    </Comment.Metadata>
                    <Comment.Text>{props.commentData}</Comment.Text>
                    <Comment.Actions>
                        <Comment.Action>Reply</Comment.Action>
                    </Comment.Actions>
                </Comment.Content>
            </Comment>
    );
}

export default Comments;
index.js

Below is the code

import React from 'react';
import ReactDOM from 'react-dom';
import { Comment } from 'semantic-ui-react';
import Comments from './Comments';
import Approvalcard from './ApprovalCard';

const App = function () {
    return (
        <Comment.Group>
            <Approvalcard>
                <Comments user="Apoorv" time="May" commentData="Comment1" />
            </Approvalcard>
            <Approvalcard>
                <Comments user="Akanksha" time="Yesterday" commentData="Comment2" />
            </Approvalcard>
            <Approvalcard>
                <Comments user="Aarav" time="Today" commentData="Comment3" />
            </Approvalcard>
        </Comment.Group>
    );
};

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

Props in ReactJS

In the previous article, Components in ReactJS, we learned how to create components and to nest them in other components. In this we can say App component is the parent component and Comments is the child component.

  • PROPS is a way of passing data from parent component to child component.
  • This way we can customize or configure the child component, displaying different data in different child component or can react to an event.
  • A child component cannot pass data back to the parent component DIRECTLY. There are ways to pass data indirectly.
  • There is no limit to the amount of information that we can share through props.
  • Props is a short form of Properties.

Let’s continue with the Components article.

In the below code, we have created three properties: user, time, commentData.

index.js

This file has the parent component and props are passed from parent component to child component. Hence we are creating the props in index.js and will pass them to Comments.js which has the child component.
Below is the code

import React from 'react';
import ReactDOM from 'react-dom';
import { Comment } from 'semantic-ui-react';
import Comments from './Comments';

const App = function () {
    return (
        <Comment.Group>
            <Comments user="Apoorv" time="May" commentData="Comment1" />
            <Comments user="Akanksha" time="Yesterday" commentData="Comment2" />
            <Comments user="Aarav" time="Today" commentData="Comment3" />
        </Comment.Group>
    );
};

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

Below is the code

import React from 'react';
import { Comment } from 'semantic-ui-react';
import faker from 'faker';

const Comments = function (props) {
    return (
        <Comment>
            <Comment.Avatar src={faker.image.avatar()} />
            <Comment.Content>
                <Comment.Author as='a'>{props.user}</Comment.Author>
                <Comment.Metadata>                  
                    <div>{props.time}</div>
                </Comment.Metadata>
                <Comment.Text>{props.commentData}</Comment.Text>
                <Comment.Actions>
                    <Comment.Action>Reply</Comment.Action>
                </Comment.Actions>
            </Comment.Content>
        </Comment>
    );
}

export default Comments;
{props.commentData} this is how we use values of props in child component.

Below is the output of above code

Components in ReactJS

    • A Component in ReactJS can be anything that can be placed on our application’s UI: a button, label, div tag, heading tag, etc.
    • Components can be categorized in two categories
      • Functional Components: We can use them when we want to show simple content to the user without a lot of logic behind it.
      • Class-based Components: We use this components for complex logic like if we want your application to respond to user input, or make a network request etc. Benefits are:
        • We can easily organize our code
        • Can use ‘state’ to handle user inputs
        • It understands lifecycle events like to do tasks when application starts
  • Component Nesting: We can show one component inside another another component.
  • Component Reusability: We can create a component which can be reused multiple times throughout the application.
  • Component Configuration: We should create a component that should be easy to configure.

Let’s create a sample application where we are creating a component in a separate file, and nesting it into another component.
We have already created a Sample Application. Let’s continue with this one.
We will be creating a Comments component using Semantic UI React. We will be generating the sample data using FakerJS.

Comments.js
  • Create a new file in src folder with the name Comments.js
  • Write the below code in this file. This is a Functional Component.
import React from 'react';
import { Comment } from 'semantic-ui-react';
import faker from 'faker';

const Comments = function () {
    return (
        <Comment>
            <Comment.Avatar src={faker.image.avatar()} />
            <Comment.Content>
                <Comment.Author as='a'>{faker.name.firstName()}</Comment.Author>
                <Comment.Metadata>
                   
<div>{faker.date.weekday()}</div>

                </Comment.Metadata>
                <Comment.Text>{faker.random.word()}</Comment.Text>
                <Comment.Actions>
                    <Comment.Action>Reply</Comment.Action>
                </Comment.Actions>
            </Comment.Content>
        </Comment>
    );
}

export default Comments;
  • export statement is used so that we can use this component in other files.
index.js

Place the below code in index.js file

import React from 'react';
import ReactDOM from 'react-dom';
import { Comment } from 'semantic-ui-react';
import Comments from './Comments';

const App = function () {
    return (
        <Comment.Group>
             <Comments />
             <Comments />
             <Comments />
        </Comment.Group>
    );
};

ReactDOM.render(<App />, document.getElementById('root'));
    • import Comments from ‘./Comments’ is used to import the data from Comments.js file.
    • This is how we are placing the Comments component in the file. We can REUSE a single component multiple times and NEST it under other components.
             
<Comment.Group>
   <Comments />
   <Comments />
   <Comments />
</Comment.Group>          
  • There should only be one parent element to return. If you try to return more than one parent component, you will get an error: JSX expressions must have one parent element.

Below is the output of above code

You can also convert it into ES6 function syntax by using arrow function. We recommend using this syntax as it has added advantages like we ca use this keyword with arrow functions, etc.

// Using ES6 function syntax (arrow function syntax) to declare Functional Components
const Comments = () => {
  // same as above
}

Generate fake data in ReactJS

PLEASE NOTE: This is a way to generate fake data and should not be used in production environment.

We sometimes need the data in our sample code which looks like a real one, but is fake. We use this so that our application looks more real and can make the necessary changes.

I used FakerJS library to generate fake data in our application.
You can scroll down the link (https://github.com/marak/Faker.js/) to look for usage and other information.
Below are the steps to generate fake data for ReactJS application

  • Open NodeJS Command prompt. Move to the project where you want to generate the fake data. Install faker library using below command
npm install --save faker

Use import statement to import the faker library in your file.
Below is a sample code

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

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>{faker.commerce.color()}}</Breadcrumb.Section>
            </Breadcrumb>
        </div>
    );
};

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

Below is the output of above code

The DRAWBACK of using Faker is that the data changes on every page refresh. As we are using Faker to generate the last part of Breadcrumb in our example, you will not be able to see the same color value. It will be different.

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).

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