Learn React JS — Build a Portfolio Single Page Application (SPA)

Learn React JS — Build a Portfolio Single Page Application (SPA)

How to create your portfolio website using React.js

Things you’ll soak in:

  1. Creating and implementing custom Components.
  2. Working with external components.
  3. Working with Props.
  4. Working with States.
  5. Dynamic Rendering.
  6. React Routing.
  7. and Using CSS in React JS.

Let’s understand some concepts…

React follows Component architecture, which means every part of a web app or website is a component, all are made separately and finally fitted into a parent component which is then rendered.

A Component is a Javascript File, for example, you want to create a sidebar component then you have to create a “Sidebar.js” file.

A component can be of two types:-

  1. Sub-Component
    A sub-component is a component that resides inside of another component.
  2. Parent Component
    A Parent component is a component in which sub-components reside in.

How does a “Component” look like in code?

“ YourComponentName.js ”

import React, { Component } from 'react'
class YourComponentName extends Component {
render() {
return (
<div>
{/* Your Html/JSX code goes here */}
<h1>This is my component</h1>
</div>
)
}
}
export default YourComponentName

All the components have a parent component, it might be either “App.js” or some other component.

import React, { Component } from 'react';

That’s a common line of code you’ll see in almost all the components everywhere. In that, we are importing React and Component class from the ‘react’ module. Which enables us to create custom components.

class YourComponentName extends Component {

This is a class component, replace “YourComponentName” to whatever name you want.

render() {
return (
<div>
<h1>This is my component</h1>
</div>
)

The render() method along with the return() method renders the content into the DOM.

And for now “YourComponentName.js” component will return “This is my component”.

export default YourComponentName

The above line of code is very important, make sure you add it compulsory, “export” keyword defines what are all the methods(functions) that should be accessible to the component importing this component.

Now that the component is built “How to use it”?

Once a component is built, we import it in the parent component or in the “App.js” file according to its functionality.

for now, let’s consider you are importing “YourComponentName.js” in “ParentComponent.js”

import YourComponentName from './YourComponentName.js'

and then the imported component is accessed just like an HTML tag inside the return() method of “ParentComponent.js”.

<YourComponentName> </YourComponentName>

now “ParentComponent.js” will look like this

import React, { Component } from 'react'
import YourComponentName from './YourComponentName.js'
class ParentComponent extends Component {
render() {
return (
<div>
<YourComponentName> </YourComponentName>
</div>
)
}
}
export default ParentComponent

At the time of rendering “<YourComponentName> </YourComponentName>” will be replaced by “<h1> This is my component </h1>” as “YourComponentName.js” is returning that <h1> tag.

If you call the “<YourComponentName> </YourComponentName>” two times then “This is my component ”will be rendered two times, meaning every time a component is called the return() method of that component is called.

What is App.js?

The “App.js” file is like the Parent container of all the components, all the parent components are imported into this “App.js” file. This is the final file that will be rendered into the Browser.

What are Props?

Props are just like parameters that are passed in a function or attributes in HTML tags, but these are user-defined, they carry some inputs to the component.

<!--For example consider a component "ComponentX" imported in some other component "ComponentY.js". "prop1" and "prop2" are the user-defined props. -->
<ComponentX prop1="xyz" prop2="zyx" ></ComponentX>
/* This is how props values are accessed in ComponentX.js. Sent from "ComponentY" */
{this.props.prop1} //returns xyz
{this.props.prop2} //return zyx

Props sent to a component is accessed through the “props” object.

What are States?

Components data will be stored in the component’s State just like a variable. This state can be modified based on user action or other action. when a value of a component’s state is changed React will re-render that component to the browser.

States are defined inside the constructor of the component class.

class YourComponentName extends Component {
constructor(props)
{
super(props);
this.state={
'myname':'Abdul wahid naafi',
'myage':'20'
}
}
render(){

here “ this.state ={} ” is the state variable and we define each state as an object inside of it. ‘myname’ and ‘myage’ are two states with some values.

To access these state values

this.state.myname //returns 'Abdul wahid naafi'
this.state.myage //returns '20'

let’s take our “YourComponetName.js” component and see states in action.

import React, { Component } from 'react'
class YourComponentName extends Component {
constructor(props)
{
super(props);
this.state={
'myname':'Abdul wahid naafi',
'myage':'20'
}
}
render() {
return (
<div>
{/* Your Html/JSX code goes here */}
<h1>This is my component</h1>
<h2>My Name is {this.state.myname}</h2>
<h3>My Age is {this.state.myage}</h3>
</div>
)
}
}
export default YourComponentName

To access javascript variables, methods, states inside return() method, insert the javascript code inside “ {} ” curly brace, it’s called “JSX”.

now the output of “YourComponetName.js” component is

This is my component
My Name is Mainak Das
My Age is 22

To modify the values of the state object

this.setState({'myage':'19'},()=>{ //this is a callback fucntion });

setState method is used to modify state values.

Let’s take our “YourComponetName.js” component to see setState in action.

import React, { Component } from 'react'
class YourComponentName extends Component {
constructor(props)
{
super(props);
this.state={
'myname':'Mainak Das',
'myage':'22'
}
}
changemyage= ()=>
{
this.setState({'myage':'19'},()=>{ alert("Age Modified ") });
}
render() {
return (
<div>
{/* Your Html/JSX code goes here */}
<h1>This is my component</h1>
<h2>My Name is {this.state.myname}</h2>
<h3 onClick={this.changemyage}>My Age is {this.state.myage}</h3>
</div>
)
}
}
export default YourComponentName

A function/method “changemyage()” is created in that the state ‘myage’ is modified from ‘20’ to ‘19’.

To call this method/function an “onClick” listener is added to <h3> tag calling the “changemyage()” method.

Once the “changemyage()” method fires up the state ‘myage’ is modified and on successful modification, an alert message will be shown telling “Age Modified”.

What Single Page Application (SPA) is?

In Wikipedia, it’s simply stated as:

A single-page application (SPA) is a web application or website that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server.
in our project, the right side of the webpage (“contents” as shown in the layout below) will be rewritten every time the user navigates to a new route(Home, About, Education, etc.,).

Now let’s get started with Building the portfolio website using React JS

If “Node JS” is not installed, <ahref=”https://nodejs.org/en/download/” rel=”noopener nofollow”>Download Node JS and install it.

I use Visual Studio Code for most of my React JS project and I highly recommend you to use.

Now, create a new folder, name it whatever you want.

  1. Open vs code.
  2. Press ctrl-shift-n (cmd-shift-n) to open a new vs code window.
  3. in the new window, click the “Open Folder” blue button on the Explorer pane,
  4. Browse and select the folder you created.
  5. Go to View → Terminal to open a terminal inside vs code.

After that, create a React JS project using “create-react-app” CLI, now name the project whatever you want for now I’ll name it as “Portfolio_Website_ReactJS”.

$ npx create-react-app Portfolio_Website_ReactJS

after you get the message “Happy Hacking”, move inside the project directory

$ cd Portolio_Website_ReactJS

Folder structure for this project!

folder structure

Inside the “src” folder, create three new folders and name them “components”, “contents”, and “img” respectively.

Inside the “Components” folder

Create the below components as javascript files in the “ components ” folder.

  • Navbar.jsThis component is the sidebar and will hold a set of “NavItems” components(Home, About, Education, Skills, Contact). It’s just the pink and blue gradient box.
  • NavItem.js This component will be the navigation items (e.g. Home, About, Education,…).
  • Social.jsThis component holds the Social media icon with links.
  • Widecard.js
    This component will hold the Education Details (as shown in the final result GIF above).

Inside the “contents” folder

The contents folder will contain the contents to be rendered on the right side of the page based on the route(Home, About, Education, etc.,).

Create the below-mentioned javascript files in the “contents” folder.

  1. Home.js
  2. About.js
  3. Education.js
  4. Skills.js
  5. Contact.js

Now your project directory should look like this:

folder structure inside

Now let’s jump into coding

Open App.js and remove all the codes inside the render() method.

Remove all the “imports” except

import React from ‘react’;
import ‘./App.css’;

Now open App.css and remove all the styles(code) and save both the files.

We will be adding all our CSS code to the “App.css” file.

Add these lines of CSS first for this project

@import url('https://fonts.googleapis.com/css?family=Raleway:300,400,500,700&display=swap');
:root{
--sidebar-flex:1.5;
--condiv-flex:6;
--fontsize-p:1.2rem;
--fontsize-nav:1.6rem;
--typing-font:3rem;
}
*
{
margin:0;
padding: 0;
}
body
{
font-family: 'Raleway';
}
.App
{
display: flex;
width: 100vw;
min-height: 100vh;
}
/* .condiv class is for the right side content container*/
.condiv
{
padding: 100px ;
background-color: #f4f5f9;
flex:var(--condiv-flex);
}

Navbar is just the wrapper of the Navitem, its just that pink blue gradient box that will contain the Navitem.

Navitem” is the sub-component and “Navbar” is the parent component.

Open “Navbar.js”

import React, { Component } from 'react';
import Navitem from './Navitem';
// We'll code Navitem.js later for now let's focus on Navbar.js
// “Navitem” is the sub-component.
class Navbar extends Component {
   
    render() {
        return (
            <nav>
            <ul>
            <Navitem item="Home" tolink="/" ></Navitem>
            <Navitem item="About" tolink="/about" ></Navitem>
            <Navitem item="Education" tolink="/education"></Navitem>
            <Navitem item="Skills" tolink="/skills"></Navitem>
            <Navitem item="Contact" tolink="/contact"></Navitem>
            </ul>
            </nav>
            )
        }
    }
    
export default Navbar

Inside the <ul> tag we have

<Navitem item="Home" tolink="/"></Navitem>

<Navitem> component tag with two props (“item” and “tolink”). It just takes the content from here and delivers there in the “Navitem” component.

In here “item” prop holds the Navigation item name (Home, About, Education, etc,.). And “tolink” prop holds the Navigation route (“/”, “/about”, “/education”, etc.,)

Five Navitem components are created and props are set.

Styling the Navbar

Open App.css and copy-paste the below CSS styles and save.

nav
{
padding:60px 30px 0px 30px ;
flex:var(--sidebar-flex);
background: rgb(238,103,143);
background: linear-gradient(180deg, rgba(238,103,143,1) 50%, rgba(132,124,252,1) 80%);
}
Go to terminal and type the following
npm install react-router-dom -g --save

navbar

“react-router-dom” is a node module used to perform routing operations in React JS.

import { Link } from "react-router-dom";

This will import the “Link” class from the “react-router-dom” module.

It acts just like the “Anchor <a>” tag in HTML.

import React, { Component } from 'react';
import { Link } from "react-router-dom";
class Navitem extends Component {
render() {
return (
<li>
<Link to={this.props.tolink} >
{this.props.item}
</Link>
</li>
)
}
}
export default Navitem

Getting the values of “item” and “tolink” prop and setting to the Link component.

<Link> tag is the component imported above from the “react-router-dom” as I mentioned they act just like Anchor tag in HTML, in there we have an attribute called “href” to define the URL, in here for the Link tag we have “to” attribute, it’s not an attribute it is a prop of Link component.

Time to do some CSS

Open “App.css”, add your styles, and save.

nav ul
{
  font-size:var(--fontsize-nav) ;
  text-align: center;
  list-style-type: none;
  text-decoration: none;
  color: white !important;
}
nav ul li
{
  margin:40px;

Now, let’s do something like whichever “Navitem” is clicked I want that Navitem text to be styled “Bold”.

We’ll be adding a CSS class “.active” to that “Navitem” which is clicked.

/* css for active class */
.active
{
font-weight: bolder;
}

For this, we’ll create a Function that will take the “Navitem’s id” as an input parameter and set that to a state object called “NavItemActive” on the Navbar component, and then the CSS “.active” class will be added to that element whose id is stored in that “NavItemActive” state object.

constructor(props)
{
super(props);
this.state={
'NavItemActive':''
}
}

Now that function to add CSS class (.active) on Navitem.

activeitem=(x)=>
{
if(this.state.NavItemId.length>0)
{
document.getElementById(this.state.NavItemActive).classList.remove('active');
}
this.setState({'NavItemActive':x},()=>{
document.getElementById(this.state.NavItemActive).classList.add('active');
});
};

( “Navitem’s” id ) refers to the DOM element ID of the Navitem(Home or About or Education …)

The “activeitem()” function or method takes an input parameter “x” which is the clicked Navitem’s ID. It will then check if there’s already anything(any element’s ID) stored in the “NavItemActive” state object if TRUE then it’ll remove the CSS “.active” class from that element, else it’ll set the state object to the Navitem’s ID which’s clicked by the user. And then a callback function will run which will add the CSS “.active” class to the Navitem which is clicked.

Here, we have this function/method in the “Navbar.js” component but we have to trigger it when the “Navitem” component is clicked. for that, we’ll be passing the “activeitem()” method as a prop to the “Navitem” component.

Now we have to set the “activeitem()” in the onClick attribute of the <Link> tag in “Navitem.js”

onClick={this.props.activec.bind(this,this.props.item)}

“bind” method is used to bind the current instance(1st parameter) and the input to be sent (2nd parameter).

“Navitem.js” will finally look like this

import React, { Component } from 'react';
import { Link } from "react-router-dom";
class Navitem extends Component {
render() {
return (
<li id={this.props.item}>
<Link to={this.props.tolink} onClick={this.props.activec.bind(this,this.props.item)}>{this.props.item}</Link>
</li>
)
}
}
export default Navitem

And, “Navbar.js” will finally look like this

import React, { Component } from 'react';
import Navitem from './Navitem';
class Navbar extends Component {
constructor(props)
{
super(props);
this.state={
'NavItemActive':''
}
}
activeitem=(x)=>
{
if(this.state.NavItemActive.length>0){
document.getElementById(this.state.NavItemActive).classList.remove('active');
}
this.setState({'NavItemId':x},()=>{
document.getElementById(this.state.NavItemActive).classList.add('active');
});
};
render() {
return (
<nav>
<ul>
<Navitem item="Home" tolink="/"  activec={this.activeitem}></Navitem>
<Navitem item="About" tolink="/about"  activec={this.activeitem}></Navitem>
<Navitem item="Education" tolink="/education"  activec={this.activeitem}></Navitem>
<Navitem item="Skills" tolink="/skills"  activec={this.activeitem}></Navitem>
<Navitem item="Contact" tolink="/contact"  activec={this.activeitem}></Navitem>
</ul>
</nav>
)
}
}
export default Navbar

In the <Navitem> component, added a new prop “activec” which will send the “activeitem()” function/method to Navitem component which will be then called whenever a Navitem is click.

<Navitem item="Home" tolink="/"  activec={this.activeitem}></Navitem>

Our Navbar is complete. Congratulations.

Now we have to Add this Navbar(sidebar) component to “App.js”

Open “App.js” add the following code

import React from 'react';
import './App.css';
import
{
BrowserRouter as Router,
Route,
} from "react-router-dom";
import Navbar from './components/Navbar';
function App() {
return (
<Router>
<div className="App">
<Navbar />
</div>
</Router>
)
}
export default App;

In React JS we access the CSS class with the “className” attribute.

import
{
BrowserRouter as Router,
Route,
} from "react-router-dom";

“BrowserRouter” is the parent component that holds all of your <Route> components. The <Route> components tell your app which other components to render (display) based on the route.

And are classes of the “react-router-dom” module.

“as” keyword is used to assign an alias name for the component in this project we’ll call “BrowserRouter” as “Router”.

import Navbar from './components/Navbar';

Here we are importing the “Navbar” component that we created, which is inside the “components” folder.

<Router>
<div className="App">
<Navbar />
</div>
</Router>

here the Div with className “App” is the parent div. As mentioned before a component should return only one node.

And inside that, we are calling the <Navbar /> component. You can call it as <Navbar></Navbar> also.

Now, save and run your application to test

npm start

A browser tab on the address http://localhost:3000/ will be opened, there you can see your React JS application.

Until here you might have understood

  1. How custom components are made and used.
  2. How CSS is implemented in React JS.
  3. And how props are sent and received across components.
  4. And how to define and modify/set State for a component.

Contents folder will contain the contents to be rendered on the right side of the page based on the route(Home, About, Education, etc.,).

  1. Home.js
  2. About.js
  3. Education.js
  4. Skills.js
  5. Contact.js

these are the five content pages we have to create.

home

Three things we’ll be focusing on Home.js

  1. Image element in React JS.
  2. Using external components in your React JS project.
  3. How to work with CDN in React JS.

Just as in HTML, to place an image you can use <img> tag in React JS.

But

<img src={} ></img>

In the JSX, the image element has a closing tag also.

And for image source, you have to import it first and then use it. As shown below.

import React, { Component } from 'react';
//importing the picture as "profilepic".
import profilepic from '../img/naafi_photo.png';
class XYZ extends Component {
render() {
return (
<img src={profilepic} className="profilepic"></img>
)
}
}
export default XYZ

For this project we gonna use an external React JS component called“React-typing-effect“

To install it in your project, in the terminal make sure you are in the project directory, and then run the below-mentioned command.

npm install react-typing-effect --save

once it’s installed, Import it wherever you want and use it as mentioned below.

import React, { Component } from 'react';
import ReactTypingEffect from 'react-typing-effect';
class XYZ extends Component {
render() {
return (
<ReactTypingEffect className="typingeffect" text={['I am Abdul Wahid Naafi','I am a web developer']} speed={100} eraseDelay={700}/>
)
}
}
export default XYZ

Usually in plain HTML, we paste the CDN links in the <head> tag.

Just like that, copy your CDN.

Goto your_project_directory/public/index.html

Paste the CDN there inside the <head> tag.

And use it just how you use it normally.

Now, as you learned all these concepts, check out the code for “Home.js” below you’ll understand it easily.

import React, { Component } from 'react';
import ReactTypingEffect from 'react-typing-effect';
import profilepic from '../img/naafi_photo.png';
class Home extends Component {
render() {
return (
<div className="condiv home">
<img src={profilepic} className="profilepic"></img>
<ReactTypingEffect className="typingeffect" text={['I am Abdul Wahid Naafi','I am a web developer']} speed={100} eraseDelay={700}/>
</div>
)
}
}
export default Home

we got one more thing to add, the “SOCIAL” component.

import React, { Component } from 'react';
class Social extends Component {
render() {
return (
<div class="social">
<a href="https://codepen.io/naafi" target="_blank"><i class="fab fa-codepen"></i></a>
<a href="https://github.com/naaficodes" target="_blank"><i class="fab fa-github"></i></a>
<a href="https://Instagram.com/iam_naafi" target="_blank"><i class="fab fa-instagram"></i></a>
<a href="https://www.facebook.com/abdul.w.naafi" target="_blank"><i class="fab fa-facebook-f"></i></a>
<a href="https://Linkedin.com/in/naafi" target="_blank"><i class="fab fa-linkedin-in"></i></a>
<a href="https://medium.com/@iam_naafi" target="_blank"><i class="fab fa-medium-m"></i></a>
</div>
)
}
}
export default Social

Just another simple component returning the HTML for social media links.

CSS code for “.social” class. Add the below code to “App.css”

.social
{
position: absolute;
margin-top: 20px;
display: flex;
bottom: 60px;
}
.social i
{
padding-right: 30px;
font-size: 25px;
color: #9a9b9c;
}
.social i:hover
{
color: #ffffff;
}

social js

let’s add this component to “Home.js” and complete the Home.js content.

Home.js

import React, { Component } from 'react';
import ReactTypingEffect from 'react-typing-effect';
import profilepic from '../img/naafi_photo.png';
import Social from '../components/Social'
class Home extends Component {
render() {
return (
<div className="condiv home">
<img src={profilepic} className="profilepic"></img>
<ReactTypingEffect className="typingeffect" text={['I am Abdul Wahid Naafi','I am a web developer']} speed={100} eraseDelay={700}/>
<Social />
</div>
)
}
}
export default Home

Time to route !!

Open “App.js”, modify the already existing route we made before.

<Router>
<div className="App">
<Navbar />
<Route exact path="/">
<Home />
</Route>
</div>
</Router>

We already learned what <Router> or <BrowserRouter> is.

<Route> is the subtag of <Router> or <BrowserRouter>, with <Route> we decide what content has to be rendered based on the path/URL.

<Route exact path="/">

exact” attribute is used when we have multiple identical paths.

And “exact” is used almost every time for path=”/”.

“Home.js” section is done !!

From here onwards all the processes will be smooth and quick, as you’ve learned pretty much needed to build this project.

about

this content page is pretty simple we are just returning a bunch of HTML.

import React, { Component } from "react";

class About extends Component {
  render() {
    return (
      <div className="condiv">
        <h1 className="subtopic">About Me</h1>
        <h4>Hey there,</h4>
        <h1>I'm Mainak Das</h1>
        <h3>
          Full Stack Web <u>Developer</u> | UI/UX <u>Designer</u>
        </h3>
        <br></br>
        <p>
          I started my journey in the world of computers from an young age, now
          I’m 22 years old, Pursuing my Computer Science Engineering Degree in
          Adamas University Barasat Kolkata. Web development is my center of
          interest, i always love the idea of cross-platform development, 1-n
          one code base deploy into almost any platform, which web technology
          like Javascript enables me to do. I also like creating Interactive UI
          components for better UX and share those desgin and codes to the world
          through Github and Instagram.
        </p>
      </div>
    );
  }
}

export default About;

There’s just contents to be rendered nothing else.

CSS code for the “About” section. Add the below code to “App.css”

.subtopic
{
margin:10px 10px 30px 10px !important;
}
p
{
font-size: var(--fontsize-p);
}
h1,h2,h3,h4,p
{
margin: 10px;
}

Time to route !!

Open “App.js”, modify the already existing route we made before.

<Router>
<div className="App">
<Navbar />
{/* Route for Home.js contents */}
<Route exact path="/">
<Home />
</Route>
{/* Route for About.js contents */}
<Route path="/about">
<About />
</Route>
</div>
</Router>

“About.js” section is done !!

education

For this page(Education.js), we’ll be creating a component to display education details. let’s call that component “Widecard” and we will have four props in that “title” “where” “from” and “to” respectively.

Widecard.js

import React, { Component } from 'react'
class Widecard extends Component {
render() {
return (
<div class="widecard">
<div class="compdet">
<h3>{this.props.title}</h3>
<h4 class="secondtext">{this.props.where}</h4>
<h4 class="secondtext">{this.props.from} - {this.props.to}</h4>
</div>
</div>
)
}
}
export default Widecard

In that component, we have an <h3> element to display the value of “title” prop, <h4> element to display the value of “where” prop, another <h4> element to display the value of “from” and “to” props.

CSS for Widecard

.widecard
{
border:0px solid #9a9b9c;
display: flex;
margin:30px 0px 30px 0px;
}
.widecard:hover
{
color: #1b1d20;
background-color: #ffffff;
box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
}

Let’s import this component into “Education.js”

import React, { Component } from "react";
import Widecard from "../components/Widecard";

class Education extends Component {
  render() {
    return (
      <div className="condiv">
        <h1 className="subtopic">My Education</h1>
        <Widecard
          title="B.Tech Computer Science Engineering"
          where="Adamas University"
          from="August 2017"
          to="Present"
        />
        <Widecard
          title="HSC"
          where="Bidhannagar Municipal School"
          from="2015"
          to="2017"
        />
      </div>
    );
  }
}

export default Education;

It’s simple right, on line 2 imported our “Widecard” component.

<Widecard title="B.Tech Computer Science Engineering" where="Adamas University" from="August 2017" to="Present"/>

Look how clean it looks, this is the benefit of custom components.

Let’s set the Routes

Open “App.js”

first, import the “Education.js” into “App.js”.

import Education from './contents/Education';

Now the Routes.

<Router>
<div className="App">
<Navbar />
{/* Route for Home.js contents */}
<Route exact path="/">
<Home />
</Route>
{/* Route for About.js contents */}
<Route path="/about">
<About />
</Route>
{/* Route for Education.js contents */}
<Route path="/education">
<Education />
</Route>
</div>
</Router>

OK, now the “Education” content is also done.

Our fourth content “Skills.js”

skills

In this, we’ll learn how to work with Dynamic rendering.

What is Dynamic rendering?

To generate DOM elements dynamically, for example, rendering the items in a javascript array as HTML <li> items.

Open “Skills.js”

So, now we’ll have a javascript array filled with the skillset as a state variable, and it’ll look like this.

constructor(props)
{
super(props);
this.state={
'myskills':['HTML','CSS','JS','PHP','REACT JS','FIREBASE','MIT APP']
};
}

We’ll loop through the array items and render it as <li> items.

<ul>
{this.state.myskills.map((value)=>{
return <li>{value}</li>
})}
</ul>

Instead of using a “for loop” to loop through every item in the array, we use the map() method.

In that function that’ll be called by the map method will return “<li>”.

import React, { Component } from 'react'
class Skills extends Component {
constructor(props)
{
super(props);
this.state={
'myskills':['HTML','CSS','JS','PHP','REACT JS','FIREBASE','MIT APP']
};
}
render() {
return (
<div className="condiv skills">
<h1 className="subtopic">My Skills</h1>
<ul>
{this.state.myskills.map((value)=>{
return <li>{value}</li>
})}
</ul>
</div>
)
}
}
export default Skills

Let’s set the Routes

Open “App.js”

First, import the “Skills.js” into “App.js”.

import Skills from './contents/Skills';

Now the Routes.

<Router>
<div className="App">
<Navbar />
{/* Route for Home.js contents */}
<Route exact path="/">
<Home />
</Route>
{/* Route for About.js contents */}
<Route path="/about">
<About />
</Route>
{/* Route for Education.js contents */}
<Route path="/education">
<Education />
</Route>
{/* Route for Skills.js contents */}
<Route path="/skills">
<Skills />
</Route>
</div>
</Router>

Yes! now the “Skills” content is also done.

contact

This “Contact” content page is just a simple page displaying the contact information.

Look!! the “Social” component is imported again!

This is the Advantage of components, make it once use it anytime anywhere.

import React, { Component } from 'react';
import Social from '../components/Social';
class Contact extends Component {
render() {
return (
<div className="condiv">
<h1 className="subtopic">Contact Me</h1>
<h3>Email  :   mainakdas104@gmail.com</h3>
<h3>Instagram   :   @mainak_ds</h3>
<Social />
</div>
)
}
}
export default Contact

Imported the “Social.js” component , and used <h1>, <h3> element to fill in the contents. As simple as that.

Let’s set the Routes for the last time !!!

Open “App.js”

First, import the “Contact.js” into “App.js”.

import Contact from './contents/Contact';

Now the Routes.

<Router>
<div className="App">
<Navbar />
{/* Route for Home.js contents */}
<Route exact path="/">
<Home />
</Route>
{/* Route for About.js contents */}
<Route path="/about">
<About />
</Route>
{/* Route for Education.js contents */}
<Route path="/education">
<Education />
</Route>
{/* Route for Skills.js contents */}
<Route path="/skills">
<Skills />
</Route>
{/* Route for Contact.js contents */}
<Route path="/contact">
<Contact />
</Route>
</div>
</Router>

Now Save the file

Go to terminal

Move to your project directory ( $ cd Resume_Website_ReactJS )

npm start

You’ll be served a new browser tab with your React JS Portfolio Website.

 

JavaScript Null vs Undefined

JavaScript – Null vs Undefined

Introduction

Null and Undefined are both data types in JavaScript. They both represent an empty value. Undefined is a declared variable but not assigned a value whereas Null means an empty or non-existent value.

In JavaScript, there are six primitive values. Both null and undefined are primitive values. Here is a full list:

  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol

Type of Null and Undefined

typeof(null)

Output

object
typeof(undefined)

Output

undefined

We can see that the type of null is an object but the type of undefined is undefined.

Comparison between null and undefined

If we compare both the data types we can see that if we use strict equality (===) then the result is false but if we compare them with abstract equality (==) then the result is true.

null===undefined

Output

false
null==undefined

Output

true

Summary

  • null and undefined are falsy values.
  • null !== undefined but null == undefined.
  • null and undefined are both primitives. However, an error shows that typeof null = object.

 

Unexpected identifier javascript – How to Fix Unexpected identifier Error in JavaScript?

How to Fix Unexpected identifier Error in JavaScript

Unexpected identifier javascript: Uncaught syntaxerror unexpected identifier javascript, Uncaught syntaxerror unexpected identifier node js, Javascript error unexpected identifier selenium, Unexpected identifier mysql, Syntax error unexpected identifier php, Unexpected identifier jquery, Uncaught syntaxerror unexpected token are solved by the errors with two reasons.

The error “Uncaught SyntaxError: Unexpected identifier” occurs for two reasons:

  • Misspelling a keyword, for example, Let or Class instead of let and class
  • Including a missing or extra comma, parentheses, quote, or bracket in your code.

Let us see some of the cases how does this error occur

NOTE:

You can compile the below codes in any online complier or vs code etc for more clarity

1)Giving ‘Let’ instead of ‘let’ keyword

// Here we gave Let insted of let. So, the 
// SyntaxError: Unexpected identifier occurs
Let EmpId = 1254; 

Output:

Let EmpId = 1254; 
^^^^^

SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

2) Giving ‘Class’ instead of ‘class’ keyword

// Here we gave Let 'Class' instead of class. So, the 
// SyntaxError: Unexpected identifier occurs
Class Employ { 
    
}

Output:

Class Employ { 
^^^^^^

SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

3) Giving ‘Function’ instead of ‘function’ keyword

// Here we gave Let 'Function' instead of 'function'. So, the 
// SyntaxError: Unexpected identifier occurs
Function multiply(x, y) { 
  return x * y;
}

Output:

Function multiply(x, y) { 
^^^^^^^^

SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

4)Missing comma(,)

const object = {
  // Here we missed a comma(,) to separate each key-value pair.
  // So, the  SyntaxError: Unexpected identifier occurs
  EmpName: 'Nick' 
  EmpId: 4256
};

Output:

EmpId: 4256
^^^^^

SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

The first and second cases indicate how a keyword misspelling generates an error. Generally, the keywords are case-sensitive.

You can validate your code by pasting it into an online Syntax Validator/online javascript compiler. The validator should be able to tell you which line has the error.

Alternatively, use your browser’s Console tab to find the line in which the error occurred.

Fixing Unexpected identifier Error in JavaScript

Unexpected identifier js: A great way to start is around the line where the problem occurred and look for:

  • Let, Const, Class, or Function are all misspelled or incorrect keywords.
  • Check if we are missing any colon, comma, bracket, parenthesis, or quote.
  • Also, see if we are giving an extra colon, comma, bracket, parenthesis, or quote.

To resolve the “Uncaught SyntaxError: Unexpected identifier” error, check for misspelled keywords, such as Let or Function instead of let and function, and correct any mistakes relating to missing or additional commas, colons, parenthesis, quotes, or brackets.

Let us now fix the above examples one by one to avoid SyntaxError: Unexpected identifier Error

index.js:

// Give let keyword NOT Let
let EmpId = 1254; 

// Give class keyword NOT Class
class Employ { 
    
}

// Give function NOT Function
function multiply(x, y) { 
  return x * y;
}

const object = {
  // Give a comma to separate each key-value pair
  EmpName: 'Nick',
  EmpId: 4256
};

Test Yourself:

  1. How to fix uncaught syntaxerror invalid or unexpected token?
  2. How to fix identifier expected error in java?
  3. How to fix undefined error in javascript?
  4. How to fix unexpected identifier?
  5. How to fix uncaught syntaxerror unexpected end of input?
  6. How to fix identifier has already been declared?
  7. How to fix unexpected token?

Props.children react – A quick intro to React’s props.children

INTRODUCTION

Props.children react: At the first sight, the this.props.children can be a bit overwhelming when studying class based components. As many developers and tutorials use React class based components as it gives access to state, it is very necessary to be familiar with props.children (if you are using stateless functional components) and this.props.children (if you are using class components)

What is ‘children’?

What this.props.children  does is that it displays whatever you include between the opening and closing tags when invoking a component.

A simple example

For example, in a class based component.

import React, { Component } from "react";

class Welcome extends Component {
  render(props) {
    return (
      <div>
        <p>Hello Class Component</p>
        <p>{this.props.children}</p>
      </div>
    );
  }
}
export default Welcome;

Here the component is receiving children from , say, app.js which can be passed in the manner shown below.

import Welcome from "./components/React/Welcome";

function App() {
  return (
    <>
      <div className="App">
        <Welcome children="I am a child" />
      </div>
    </>
  );
}

export default App;

As you can see, when the string “I am a child” is passed through to the Welcome component the output looks similar to what is shown below.

Hello Class Component.

I am a child 

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

 

A complex example

I will now demonstrate an error solving method via this.props.children , where if there is an error in code it will display Something Went Wrong  or if it is error free code it will simply say Error Free Code

import React, { Component } from "react";

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: true,
    };
  }

  componentDidCatch(error, info) {
    console.log(error);
  }

    render() {
        if (this.state.hasError) {
        return <h1>Something Went Wrong</h1>;
        } else if (!this.state.hasError) {
        return (<>
                   <h1>Error Free Code</h1>
                   {this.props.children};
                </>);
        }
    }
    }
export default ErrorBoundary;

So, if there is error in the code, then the first return statement will be implemented and all others will be ignored. Or else, the this.props.children that is passed via another (parent) component will be displayed.

 

CONCLUSION

I hope this shed a little bit more light on React and how you can use props.children to help you customize your app’s content while still being able to reuse the same components in my case for error checking purposes.

 

First letter uppercase js – How to uppercase the first letter of a string in JavaScript? | JavaScript Program to Convert the First Letter of a String into UpperCase

How to Uppercase the first letter of a String in JavaScript

First letter uppercase js: In this tutorial, passionate learners can grab the opportunity to study and understand how to write a JavaScript program that converts the first letter of a string into uppercase. Here, we have used two approaches with neat examples and explained How to Capitalize the First Letter of a String in JavaScript. So, check out the below links directly and learn thoroughly.

How to Uppercase the first letter of a string in JavaScript?

How to uppercase first letter in javascript: JavaScript offers several methods to capitalize a string to make the first character uppercase. Discover what are the various ways, and also find out which one is best for using with plain JavaScript.

The most common operation with strings is to make the string capitalized: uppercase its first letter, and leave the rest of the string as-is.

The best way to do this is by a combination of two functions. One uppercases the first letter, and the second slices the string and returns it starting from the second character.

const name = "flavio";
const nameCapitalized = name.charAt(0).toUpperCase() + name.slice(1);
console.log(nameCapitalized);

You can extract that to a function, which also checks if the passed parameter is a string, and returns an empty string if not.

const capitalize = (s) => {
  if (typeof s !== 'string') return ''
  return s.charAt(0).toUpperCase() + s.slice(1)
}

capitalize('flavio') //'Flavio'
capitalize('f')      //'F'
capitalize(0)        //''
capitalize({})       //''

Instead of using s.charAt(0) you could also use string indexing (not supported in older IE versions): s[0].

Some solutions online advocate for adding the function to the String prototype.

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1)
}

(we use a regular function to make use of this -arrow functions would fail in this case, as this in arrow functions does not reference the current object)

This solution is not ideal, because editing the prototype is not generally recommended, and it’s a much slower solution than having an independent function.

Don’t forget that if you just want to capitalize for presentational purposes on a Web Page, CSS might be a better solution, just add a capitalize class to your HTML paragraph and use:

p.capitalize {
  text-transform: capitalize;
}

Do Refer:

Example 1: Convert the First letter to UpperCase

Let’s see the below program on converting the first letter to uppercase. Here, the user is prompted to enter a string and that string is transferred into the capitalizeFirstLetter() function.

  • First and foremost, the string’s first character is extracted performing charAt() method. Here, str.charAt(0); gives p.
  • The toUpperCase() method changes the string to uppercase. Here, str.charAt(0).toUpperCase(); gives P.
  • The rest of the string is return by the slice() method. Here, str.slice(1); gives Programming
  • Finally, these two values are concatenated using the + operator.
// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {

    // converting first letter to uppercase
    const capitalized = str.charAt(0).toUpperCase() + str.slice(1);

    return capitalized;
}

// take input
const string = prompt('Enter a string: ');

const result = capitalizeFirstLetter(string);

console.log(result);

Output:

Enter a string: programming 
Programming

Example 2: Convert the First letter to UpperCase using Regex

Below the given program, convert the first letter of a string to uppercase by using the regular expression (regex).

  • The regex pattern is /^./ meets the first character of a string.
  • The toUpperCase() method changes the string to uppercase.
// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {

    // converting first letter to uppercase
    const capitalized = str.replace(/^./, str[0].toUpperCase());

    return capitalized;
}

// take input
const string = prompt('Enter a string: ');

const result = capitalizeFirstLetter(string);

console.log(result);

Output:

Enter a string: programming 
Programming

React js alternatives – Lightweight Alternatives to React

Lightweight Alternatives to React

React js alternatives: React.js is a marvelous JavaScript library that employs Virtual DOM. React is the prime choice of developers when it comes to building single-page applications.

Why do you need an alternative to React.js?

  • Most of the React developers find it challenging to manage the huge library size of the React.js framework. Surely you can not afford to invest in a framework that demands an exquisite memory space.
  • Secondly, React lacks MVC architecture, especially since the View functionality is not managed by its Model and Controller. Hence, you need an alternative React framework, which is view-oriented.
  • React has a steep learning curve, and developers need to invest a lot of time to learn new technology. Project ignition is delayed.
  • Many React.js developers find it hard to grasp the documentation of JSX React. Beginners are never comfortable with this framework.

In this blog, I am recalling and bringing in front of you the list of React.js alternatives that those experts realized in the tech-talk show. Along with the javascript frameworks, I have mentioned the pros and cons of each of the frameworks and their comparison with React.js.

Preact

Alternatives to react: Jason Miller introduced Preact under the open-source MIT license. You can think of Preact as a lightweight alternative to the React library for developing mobile or web applications, and progressive web apps PWA.

Preact Pros

React js alternatives: It is much compact, precise, and lightweight in size (3KB) so your application can perform faster.

  • Preact uses ES6 API, which enables you to uplift your application from React to Preact very easily. You can even adapt it as a library to create fantastic user interfaces for your project.
  • Entrepreneurs can create new projects easily by using the official CLI without the trouble of getting into Babel and Webpack configuration.
  • You can get all the help from the official website examples and Preact documentation to kick-start your application development.
  • Along with all the inspiring features of React, the Preact library also consists of some special features like the LinkedState.

Preact Cons

You do not get the context support.

  • For the stateful functionalities of your application, the createClass function is missing. Preact only allows you to use ES6 class and stateless components.
  • Preact doesn’t care about the React propTypes.
  • The community size is yet to reach the competition with React.
  • Preact lacks innovation and mostly mimics React.

Preact Vs. React

  • API: Not all the React features are present in Preact; it contains only a small part of the React Application Interface functionality.
  • Size: As I mentioned in the beginning, Preact is much lighter than React. React is 5.3 KB, whereas Preact is only 3 KB.
  • Performance: Because of being lightweight, Preact is faster as compared to React applications.

Svelte

React alternatives: Svelte is a free and open-source front-end compiler created by Rich Harris and maintained by the Svelte core team members. Svelte applications do not include framework references.

Svelte Pros

  • The building time is blazing fast when compared to React or even other frameworks. Usage of the rollup plugin as the bundler might be the secret here.
  • Bundle size is smaller and tiny when gzipped when compared to React, and this is a huge plus point. Even with the shopping cart application I built, the initial load time and the duration to render the UI is extremely low, only the chunky images I have added takes some time :).
  • Binding classes and variables are relatively easy, and custom logic is not needed when binding classes.
  • Scoping CSS <style> within the component itself allows flexible styling.
  • Easier to understand and get started when compared to other frameworks as the significant portion of Svelte is plain JavaScript, HTML, and CSS.
  • More straightforward store implementation when compared to React’s context API, granted context API provides more features, and Svelte might be simple enough for common scenarios.

Svelte Cons

  • Svelte won’t listen for reference updates and array mutations, which is a bummer, and developers need to actively lookout for this and make sure arrays are reassigned so the UI will be updated.
  • Usage style for DOM events can also be annoying, as we need to follow Svelte’s specific syntax instead of using the predefined JS syntax. Cannot directly use onClick like in React, but instead, have to use special syntax such as on:click.
  • Svelte is a new and young framework with minimal community support, thereby doesn’t have support for a wide range of plugins and integrations that might be required by a heavy production application. React is a powerful contender here.
  • No additional improvements. Ex- React suspense actively controls your code and how it runs and tries to optimize when the DOM is updated and sometimes even provides automatic loading spinners when waiting for data. These extra features and continued improvements are relatively low in Svelte.
  • Some developers might not prefer using special syntaxes such as #if and #each within their templates and instead would want to use plain JavaScript, which React allows. This might come down to personal preferences.

Svelte Vs. React

Svelte does provide noticeable improvements in certain features when compared to React. But it may not still be significant or large enough to replace React completely. React is still robust and broadly adopted. Svelte has quite some catching up to do. But concept-wise, the compiling approach taken by Svelte has proven that virtual DOM diffing isn’t the only approach to build fast reactive applications, and a good enough compiler can get the same job done as well as it gets.

Vanilla JS

Vanilla JS is nothing but plain JS without any external libraries or frameworks. Using this we can build powerful and cross-platform applications.

The major differences

Since there are so many ways to write vanilla JS, it can be difficult to pin down a list of differences that applies to 100% of apps. But here we’ll define some key differences that apply to many plain JS apps that are written without a framework.

Those differences are:

  • How the user interface is first created
  • How functionality is split up across the app
  • How data is stored on the browser
  • How the UI is updated

Is Vanilla JS worth over React

Vanilla JS is awesome but it’s not a great alternative when it comes to building huge applications with complex dynamic functionalities. Besides, it cannot create complex and efficient UIs. So if you have an app that changes frequently and drastically with thousands of pages, it is better to use a modern Javascript framework.

On the other hand, React which allows us to use reusable components and is capable of keeping the UI in sync with the state can definitely solve this problem.

Javascript global object – The JavaScript Global Object | What is a Global Object in JavaScript? | JavaScript Global Variables, Properties, Functions

The JavaScript Global Object

Javascript global object: JavaScript implements a global object which holds a kit of properties, functions, and objects that are accessed globally, without a namespace. Want to learn more about the JavaScript Global Object Variables, Functions & Properties? Then, this tutorial is the perfect one for all beginners and experienced programmers. So, dive into this page and directly get into the topic using the direct links available below.

What is a Global Object in JavaScript?

Objects in JavaScript are distinct from the Global Object. Applying the new operator, you cannot build global objects. When the scripting engine is initialized then only it comes into existence. Once the initialization is completed, the functions and constants are ready to use while coding in JavaScript.

A global object enables you to perform the below conditions −

  • It provides access to built-in functions and values. Call alert immediately like the below code snippet, with window −
alert("Demo Text");
// or
window.alert("Demo Text");
  • Even, it also provides access to global function declarations and var variables in JavaScript. Look at the below code –
<script>
         var str = "Demo Text";
         // using window
         alert( window.str );
</script>

Some of the JavaScript Global objects are:

  • Array
  • Boolean
  • Date
  • Function
  • JSON
  • Math
  • Number
  • Object
  • RegExp
  • String
  • Symbol

and errors:

  • Error
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

Window object in the Browser

In the Browser, the window object is the Global Object. Any JavaScript Global Variables or Functions can be accessed as properties of thewindowobject while programming.

Do Refer:

JavaScript Global Properties

The properties of JavaScript Global Object are:

  • Infinity
  • NaN
  • undefined

Infinity

Infinity in JavaScript is a value that represents infinity.

Positive infinity. To get negative infinity, use the  operator: -Infinity.

Those are equivalent to Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY.

Adding any number to Infinity, or multiplying Infinity for any number, still gives Infinity.

NaN

The global NaN value is an acronym for Not a Number. It’s returned by operations such as zero divided by zero, invalid parseInt() operations, or other operations.

parseInt()    //NaN
parseInt('a') //NaN
0/0           //NaN

A special thing to consider is that a NaN value is never equal to another NaN value. You must use the isNaN() global function to check if a value evaluates to NaN:

NaN === NaN //false
0/0 === NaN //false
isNaN(0/0)  //true

undefined

The global undefined property holds the primitive value undefined.

Running a function that does not specify a return value returns undefined:

const testFunc = () => {}
testFunc() //undefined

Unlike NaN, we can compare an undefined value with undefined, and get true:

undefined === undefined

It’s common to use the typeof operator to determine if a variable is undefined:

if (typeof cat === 'undefined') {

}

JavaScript Global Functions

The functions are:

  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • eval()
  • isFinite()
  • isNaN()
  • parseFloat()
  • parseInt()

decodeURI()

Performs the opposite operation of encodeURI()

decodeURIComponent()

Performs the opposite operation of encodeURIComponent()

encodeURI()

This function is used to encode a complete URL. It does encode all characters to their HTML entities except the ones that have a special meaning in a URI structure, including all characters and digits, plus those special characters:

~!@#$&*()=:/,;?+-_.

Example:

encodeURI("http://google.com/good morning/")
//"http://google.com/good%20morning/"

encodeURIComponent()

Similar to encodeURI()encodeURIComponent() is meant to have a different job.

Instead of being used to encode an entire URI, it encodes a portion of a URI.

It does encode all characters to their HTML entities except the ones that have a special meaning in a URI structure, including all characters and digits, plus those special characters:

-_.!~*'()

Example:

encodeURIComponent("http://www.example.org/a file with spaces.html")
// "http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html"

eval()

This is a special function that takes a string that contains JavaScript code and evaluates/runs it.

isFinite()

Returns true if the value passed as parameter is finite.

isFinite(1)                        //true
isFinite(Number.POSITIVE_INFINITY) //false
isFinite(Infinity)                 //false

isNaN()

Returns true if the value passed as parameter evaluates to NaN.

isNaN(NaN)        //true
isNaN(Number.NaN) //true
isNaN('x')        //true
isNaN(2)          //false
isNaN(undefined)  //true

This function is very useful because a NaN value is never equal to another NaN value. You must use the isNaN() global function to check if a value evaluates to NaN:

0/0 === NaN //false
isNaN(0/0)  //true

parseFloat()

Like parseInt()parseFloat() is used to convert a string value into a number, but retains the decimal part:

parseFloat('10.000', 10) //10     
parseFloat('10.20', 10)  //10.2   
parseFloat('10.81', 10)  //10.81

parseInt()

This function is used to convert a string value into a number.

Another good solution for integers is to call the parseInt() function:

const count = parseInt('1234', 10) //1234

Don’t forget the second parameter, which is the radix, always 10 for decimal numbers, or the conversion might try to guess the radix and give unexpected results.

parseInt() tries to get a number from a string that does not only contain a number:

parseInt('10 lions', 10) //10

but if the string does not start with a number, you’ll get NaN (Not a Number):

parseInt("I'm 10", 10) //NaN

Also, just like Number, it’s not reliable with separators between the digits:

parseInt('10.20', 10)  //10 
parseInt('10.81', 10)  //10

JS check object empty – How to Check whether an Object is Empty in JavaScript?

How to Check whether an Object is Empty in JavaScript

JS check object empty: In this article, we are going to check whether the object is empty or not in Javascript

Check whether an Object is Empty in JavaScript?

Javascript check object empty: We can check whether the object is empty or NOT in a number of ways. Let us see them one by one:

Method #1: Using Object.keys() Method

In JavaScript, use the following steps to determine whether an object is empty:

  • Pass the object to the ‘Object.keys’ method to obtain an array of all the keys of an object
  • Access the length property on the array.
  • If the length of the keys is equal to 0, the object is empty.

Using ‘Object.keys’ on an Empty Object

// This Supports in IE 9-11
// Declare an empty object 
const object = {};

// Check if the above object is empty using the Object.keys and length attribute
const chk_isEmpty = Object.keys(object).length === 0;
// If it is empty it prints true, else false
console.log(chk_isEmpty)

Output:

true

Explanation:

Here, the Object.keys() method is used to get an array of all of the keys of an object.

Using ‘Object.keys’ on a Non-Empty Object

// This Supports in IE 9-11
// Declare an empty object 
const object = {1:"Hello", 2:"this is", 3:"Btechgeeks"};

// Check if the above object is empty using the Object.keys and length attribute
const chk_isEmpty = Object.keys(object).length === 0;
// If it is empty it prints true, else false
console.log(chk_isEmpty)

Output:

false

Explanation:

Here the given object is not empty, hence it returns false

NOTE:

If the object has no key-value pairs (if it is empty), the Object.keys method returns an empty array.

Method #2: Iterating Over the Properties of Object

Another way is to iterate over the properties of an object. If the object has even a single iteration, it is not empty.

Example

// This supports in IE 6-11

// Declare an empty object and store it in a variable
const gvn_obj = {};

// Create a function say checkIsEmpty by passing the object 
// as an argument to it.
function checkIsEmpty(object) {
  // Iterate over the properties of an object using the for loop.
  // Check If the object has even a single iteration(object is not empty)
  for (const property in object) {
    // As the object is NOT empty, return false  
    return false;
  }
  // As the object is empty, return true  
  return true;
}

// Pass the given object as an argument to the above checkIsEmpty
// function and print the result
console.log(checkIsEmpty(gvn_obj)); 

Output:

true

Method #3: Using Object.entries() Method (ECMA 7+)

// Declare an empty object and store it in a variable
const gvn_obj = {};

// Check if the above object is empty using the Object.entries and length attribute
const chk_isEmpty = Object.entries(gvn_obj).length === 0 && gvn_obj.constructor === Object

//If it is empty it prints true, else false
console.log(chk_isEmpty)

Output:

true

Method #4: Using hasOwnProperty() function (Pre-ECMA 5)

Example1

// Declare an empty object and store it in a variable
const gvn_obj = {};

// Create a function say checkIsEmpty by passing the object 
// as an argument to it.
function checkIsEmpty(gvn_obj) {
  for(var property in gvn_obj) {
     // using hasOwnProperty() function to check if an object is empty or NOT
    if(gvn_obj.hasOwnProperty(property)) {
      return false;
    }
  }
  return JSON.stringify(gvn_obj) === JSON.stringify({});
}

// Pass the given object as an argument to the above checkIsEmpty
// function and print the result
console.log(checkIsEmpty(gvn_obj));

Output:

true

Example2

// Declare an object and store it in a variable
const gvn_obj = {1:"Hello", 2:"this is", 3:"Btechgeeks"};

// Create a function say checkIsEmpty by passing the object 
// as an argument to it.
function checkIsEmpty(gvn_obj) {
  for(var property in gvn_obj) {
     // using hasOwnProperty() function to check if an object is empty or NOT
    if(gvn_obj.hasOwnProperty(property)) {
      return false;
    }
  }
  return JSON.stringify(gvn_obj) === JSON.stringify({});
}

// Pass the given object as an argument to the above checkIsEmpty
// function and print the result
console.log(checkIsEmpty(gvn_obj));

Output:

false

Fix – Cannot use import statement outside module

Fix - Cannot use import statement outside module

Cannot use import statement outside a module node: When we use the ES6 Modules syntax in a script that wasn’t loaded as a module, we get the “SyntaxError: Cannot use import statement outside a module” error. Set the type property to the module when loading a script or in your package to fix the error. For Node apps, package.json is used.

Cannot use import statement outside module(Fix)

Cannot use import statement outside a module javascript: Below are some of the fixes for Cannot use import statement outside module error:

Fix #1: Adding type=”module” in index.html(main Page)

Nodejs cannot use import statement outside a module: Set the type attribute to the module when loading the script in your HTML code to fix the problem.

Solution:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- adding type as module in the script   -->
    <script type="module" src="index.js"></script>
</body>
</html>

In our JavaScript code, we can now use the syntax of the ES6 module.
It’s important to remember that any JavaScript files that use the syntax of the ES6 module must have the type attribute set to the module.

index.js

// importing from the loadash module
import _ from 'lodash';

// printing the unique values in the array by passing the array as an argument to the uniq() function
console.log(_.uniq([4,2,5,8,4,4]));

Output:

[4,2,5,8]

Fix #2: Adding type=module in Node.js

Cannot use import statement outside a module: When working with Node.js, you must set the type property in your package to the module. To use ES6 module imports, you’ll need a package.json file.

If your project doesn’t have a package.json file, create one with the npm init -y command in the project’s root directory.

npm init --y

package.json:

{
  "name": "btechgeeks",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type":"module"
}

In your Node.js application, you can now use the syntax of the ES6 module.

index.js

// importing from the loadash module
import _ from 'lodash';

// printing the unique values in the array by passing the array as an argument to the uniq() function
console.log(_.uniq([4,2,5,8,4,4]));

Output:

[4,2,5,8]

Importing from another user created module:

You must add the .js extension when importing local files with the type attribute set to module.

btechgeeks.js

function mySum(a, b) {
  return a + b; 
}
export default mySum;

index.js

// importing mysum function from btechgeeks.js module using the import keyword
import mysum from './btechgeeks.js';

// passing some random two values to the mysum() function of the btechgeeks module and printing the summ
console.log('sum is:',mysum(11,17));

Output:

sum is: 28

If we remove the .js from the import then:

index.js

// importing mysum function from btechgeeks.js module using the import keyword
import mysum from './btechgeeks';

// passing some random two values to the mysum() function of the btechgeeks module and printing the summ
console.log('sum is:',mysum(11,17));

Output:

node:internal/process/esm_loader:94
internalBinding('errors').triggerUncaughtException(
^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\cirus\Desktop\LinkedIn\btechgeeks' imported from C:\Users\cirus\Desktop\LinkedIn\index.js
Did you mean to import ../btechgeeks.js?
at new NodeError (node:internal/errors:371:5)
at finalizeResolution (node:internal/modules/esm/resolve:418:11)
at moduleResolve (node:internal/modules/esm/resolve:983:10)
at defaultResolve (node:internal/modules/esm/resolve:1080:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:530:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:251:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:79:40)
at link (node:internal/modules/esm/module_job:78:36) {
code: 'ERR_MODULE_NOT_FOUND'
}

Fix #3: Using require()

If none of the above options worked, try substituting require() for the import/export syntax.

// Using the require() function to import some random package
const myRandomFunction = require('some-package');

// For named exports enclosed the function in {}
const {someRandomFunction} = require('some-package')

Note:

If you try to run your source files that use ES6 module import/export syntax instead of your compiled files from your build directory, you’ll get the “Cannot use import statement outside module” error. Make sure that your compiled files are only executed from the build/dist directory.

Javascript cannot read property of undefined – How to Fix Cannot read Property of Undefined Error in JavaScript

How to Fix Cannot read Property of Undefined Error in JavaScript

Javascript cannot read property of undefined: There are three main causes of the “Cannot read property of undefined” error:

  • When we access a property on a variable that holds an undefined value.
  • When we access a non-existent property on a DOM element.
  • When we Insert the JavaScript <script/> tag above the HTML, where the DOM elements are declared.

The error most typically happens when you attempt to access a property on a variable that has an undefined value.

index.js:

const employ = undefined;

// Here the variable `employ` is undefined so when we try to
// access the `salary` property on the above variable that holds an
// undefined value we get an ERROR
employ.salary;

Output:

employ.salary;
^

TypeError: Cannot read property 'salary' of undefined
at Object.<anonymous> (/tmp/MOncfvGk3U.js:6:8)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here the variable `employ` is undefined so when we try to access the `salary` property 
on a variable that holds an undefined value we get an ERROR

Fixing Cannot read Property of Undefined Error in JavaScript

Method #1: Using Optional Chaining(.)

Cannot read property of undefined javascript: To fix the “Cannot read property of undefined” error, use the optional chaining (.) operator to ensure that the variable, for example employ.salary, is not null before accessing it.

Instead of throwing an error, the operator short-circuits if the variable is undefined or null.

// Take a variable and initialize its value with undefined
const employ = undefined;

// Print the salary property/attribute of the employ if it is doesn't exists then it prints undefined
console.log(employ.salary); 
console.log(employ.salary.month); 

Output:

Undefined
Undefined

Explanation:

Javascript cannot read property of undefined: The optional chaining (.) operator enables us to access an object’s property without throwing an exception if the reference is invalid.

If the reference is equal to undefined or null, the optional chaining (.) operator returns undefined instead of raising an error.

Method #2: Using if-Else Conditional Statements

// Take a variable and initialize its value with undefined
const employ = undefined;

// Check if the salary attribute is present in employ using optional chaining(.) and if conditional statement
if (employ.salary) {
// If is is true(exists) print that corresponding value 
  console.log(employ.salary);
} else {
    // Else print some random text for acknowledment
  console.log('The employ.salary is NOT found');
}

Output:

The employ.salary is NOT found

Method #3: Using logical AND (&&) operator

// Take a variable and initialize its value with undefined
const employ = undefined;

// Here we use logical AND(&&) operator to check whether the property/attribute exists or not
console.log(employ && employ.salary); 

Output:

undefined

Explanation:

Here we used the logical AND (&&) operator, which ignores the value to the right 
if the value to the left is false (example- undefined).

When trying to access an array element at an index that does not exist in the array, you frequently obtain undefined results.

// Give an empty array and store it in a variable
const gvn_arry = [];

// This is a BAD approach
// Here we get i.e, Cannot read property 'website' of undefined
console.log(gvn_arry[0].website); 

// This is a GOOD approach
console.log(gvn_arry[0].website); 

// This is a GOOD approach
console.log(gvn_arry[0] && gvn_arry[0].website); 

Output:

Undefined

Undefined

Before attempting to access a variable, ensure that it has been declared in your code; otherwise, you will receive the “X is not defined” error.

Accessing a non-existent property on a DOM element.

Another common cause of the error is attempting to access a property on a DOM element that does not exist.

To resolve the “Cannot read property of undefined” problem, verify that the DOM element you are attempting to access exists. When attempting to access the property at a non-existent index after using the getElementsByClassName() method, the error is frequently thrown.

index.js:

// Get the element by class name which doesn't exist

const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes );

// Here we get an error => Cannot read properties of undefined (reading 'innerHTML')
console.log(htmlboxes [0].innerHTML);

Output:

Cannot read properties of undefined (reading 'innerHTML')

Instead, correct the class name and use the optional chaining (.) operator to see if the property is present in the element at the index 0.

Using Optional Chaining and If else Conditional statements:

// Get the element by class name which doesn't exist 
const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes ); 

// Check if the element exists using the optional chaining(.)
if (htmlboxes[0].innerHTML) {
  console.log(htmlboxes [0].innerHTML);
} else {
  // If the element doesnt exist then print some random acknowledgement
  console.log('The element is not FOUND');
}

If the element at index 0 has the innerHTML property, the if block is executed; otherwise, the else block is executed.

To resolve the “Cannot read property of undefined” error, place the JS <script/> tag at the bottom of the body. After the HTML elements have been declared, the JS script tag should be inserted.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <script src="index.js"></script>

    <!-- The HTML elements must be above the JS script tag,
    otherwise they cannot be accessed
    This is a BAD approach-->
    
    <div class="box">Btechgeeks</div>
  </body>
</html>

The index.js script tag is executed before the declaration of the div element with the class name box.

The div element will not be available if you try to access it in the index.js script, resulting in the error.

index.js:

// Get the element by class name which doesn't exist 
const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes); // []

// Here we get Cannot read properties of undefined (reading 'innerHTML') Error
console.log(htmlboxes[0].innerHTML);

So, the JS script must be placed at the bottom of the body, after the HTML elements have been declared.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <!--Here the HTML elemets are declared first -->
    <div class="box">Btechgeeks</div>

    <!-- Here the Js script tag is palced at the bottom of the body after the declaration of HTML elements
    which is a GOOD Approach>
    <script src="index.js"></script>
  </body>
</html>
Inside the index.js script, the div element with the class name box is now accessible.

index.js:

// Get the element by class name which doesn't exist 
const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes); // []

// Here we get Cannot read properties of undefined (reading 'innerHTML') Error
console.log(htmlboxes[0].innerHTML);

In Brief

When attempting to access a property on an undefined value, the “Cannot read property of undefined” error occurs.

Undefined values are frequently returned when:

  • when we access a property on an object that does not exist.
  • when we access an index in an array that does not exist