Monday, November 21, 2022

React HelloWorld App - First React App

As a tradition whenever you start learning any new framework or programming language you start with a Hello World program. In this tutorial we'll see how to create first React app which is going to be a Hello World React app.


Generate React Project using Create React App

If you want to create a React project named myreact-app go to the folder where you want to create this project and run the following command.

npx create-react-app myreact-app

This command takes care of installing all the required packages, creating a React project structure with all the proper configuration so that we can start writing components.

Read more about Create React App in this post- Creating a New React Project - create-react-app

Running default app

Once project is created change directory to the created project folder.

cd myreact-app

Then run following command to run the app in development mode. This command compiles the app and start the development server.

npm start

If there is no error then it should automatically run the application in your browser or once you see the application is successfully compiled open the browser and type URL- http://localhost:3000/ to see the default application.

React default app

So, create-react-app generates a React project, even has some generated code which you can run and verify that everything it fine with your project. If everything has gone as expected let's make changes in the project to display Hello World.

HelloWorld React application

It will be easy for you to see the project structure and create new files or edit existing files if you are using an editor. Visual Studio Code is a preferred editor for React development so we'll use that.

Open Visual Studio Code and select Open folder. Select the created myreact-app folder to open it.

In the project there will be a App.js file with in the src folder.

React App Structure

App.js file has the code that displays the default view.

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App

Since we are going to write our own code now, so delete the code in App.js and replace it with the following code.

function App() {
  return (
    <div className="App">
      <h2>Hello World from React</h2>
    </div>
  );
}

export default App;

Because of hot reloading any changes you have made in the code will automatically refresh the app in the browser to reflect those changes. So, you should see "Hello World from React" displayed.

Creating HelloWorld Component

In React you will create many components which taken as a whole define your application. Making changes in App.js to display Hello World is ok but not a true reflection of how you will actually develop your app in React. So, now we'll create a HelloWorld component that does the job of displaying Hello World.

In React, components come in two types

  1. Functional components- Written as Java Script functions. Functional component with React hooks is the preferred way to write React code now.
  2. Class components- Written as a ES6 class that extends from React.Component

HelloWorld component as a functional component

In the src folder of your project create a new folder named 'Components' and with in that a sub-folder named 'Hello-World'. With in 'Hello-World' folder create a new file named 'HelloWorld.js'.

In HelloWorld.js write the following code.

const HelloWorld = () => {
    return <h2>Hello World from React</h2>
}
export default HelloWorld;

Some points to note here are-

  1. Custom component name is always written in title case in React.
  2. Functional component is just a Java Script function and here it is written as an arrow function.
  3. In React you use JSX which is a syntax extension for JavaScript that lets you write HTML-like markup with in a JavaScript file. Read more about JSX in this post- JSX in React
  4. You need to export your component so that it can be imported into other componenects with the import declaration.

The components you write are effectively React elements which means you can use these components by wrapping them inside a tag just like HTML tags. If you want to use your HelloWorld component inside App component that's how you can do it.

import HelloWorld from "./Components/Hello-World/HelloWorld";

function App() {
  return (
    <div className="App">
      <HelloWorld />
    </div>
  );
}

export default App;

Some points to note here are-

  1. You need to import components before using them in other React components.
  2. You can use component by wrapping it inside a tag. <HelloWorld />

With these changes you should now see your custom HelloWorld component being rendered.

React Hello World Example

HelloWorld component as a class component

If you want to write HelloWorld component as a class component then create a new file named HelloWorldClass.js inside HelloWorld folder and write the following code.

import React from "react";

class HelloWorldClass extends React.Component {
  render() {
    return <h2>Hello World From React ClassComponent</h2>;
  }
}
export default HelloWorldClass;

Some points to note here are-

  1. A class component is an ECMAScript 6 (ES6) JavaScript class.
  2. Class components extend from the React.Component class.
  3. The render() method is required in a React.Component subclass and used to return an HTML element.

In order to render HelloWorldClass component change the import and tag in App.js file.

import HelloWorldClass from "./Components/Hello-World/HelloWorldClass";

function App() {
  return (
    <div className="App">
      <HelloWorldClass />
    </div>
  );
}

export default App;

That's all for this topic React HelloWorld App - First React App. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Creating a New React Project - create-react-app
  2. Access Modifiers in Java

You may also like-

  1. Angular Project Structure With File Description
  2. Lambda expressions in Java 8
  3. How HashMap internally works in Java

Sunday, November 20, 2022

Java BufferedWriter Class With Examples

Java BufferedWriter class is used to write text to a character-output stream. This class is used as a wrapper around any Writer (FileWriter and OutputStreamWriter) whose write() operations may be costly. java.io.BufferedWriter makes the write operation more efficient by buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.

Java BufferedWriter constructors

  • BufferedWriter(Writer out)- Wraps the passed Writer and creates a buffering character-input stream that uses a default-sized input buffer. Default buffer size for BufferedWriter is 8192 bytes i.e. 8 KB.

    For example-

     BufferedWriter out = new BufferedWriter(new FileWriter("resources/abc.txt"));
     
  • BufferedWriter(Writer out, int sz)- Wraps the passed Writer and creates a new buffered character-output stream that uses an output buffer of the given size.

Java BufferedWriter methods

Methods in BufferedWriter class are as given below-

  • flush()- Flushes the stream.
  • newLine()- Writes a line separator.
  • write(int c)- Writes a single character.
  • write(char[] cbuf, int off, int len)- Writes a portion of an array of characters. Parameter off is the offset from which to start reading characters and parameter len is the number of characters to write.
  • write(String s, int off, int len)- Writes a portion of a String. Parameter off is the offset from which to start reading characters and parameter len is the number of characters to write.

Java BufferedWriter examples

For using BufferedWriter steps are as follows-

  1. Create an instance of BufferedWriter wrapped around another Writer.
  2. Using that instance to write to a file.
  3. Close the stream, you should close the resources in finally block or you can use try-with-resources to automatically manage resources.

1. Using write(int c) method of the Java BufferedWriter class to write single character to a file.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteRW {
  public static void main(String[] args) throws IOException {
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\Temp\\write.txt"))){
      bw.write(65); //writes A
      bw.write(66); //writes B
      bw.write(67); //writes C
    }
  }
}

2. Using write(char[] cbuf, int off, int len) method of the Java BufferedWriter class to write portion of a character array.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteRW {
  public static void main(String[] args) throws IOException {
    String str = "This is a test String";
    char[] buffer = str.toCharArray();
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\Temp\\write.txt"))){
      bw.write(buffer, 0, 7);// takes portion from index 0..6
    }
  }
}

3. Using write(String s, int off, int len) of the Java BufferedWriter class to write a portion of a String.

public class FileWriteRW {
  public static void main(String[] args) throws IOException {
    String str = "This is a test String";
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\Temp\\write.txt"))){
      bw.write(str, 0, 7);// takes substring from index 0..6
    }
  }
}

4. Using newLine() method of the Java BufferedWriter class.

public class FileWriteRW {
  public static void main(String[] args) throws IOException {
    String str = "This is a test String";
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\Temp\\write.txt"))){
      bw.write(str, 0, 7);// takes substring from index 0..6
      bw.newLine(); // new line
      bw.write(str, 7, str.length()-7);
      bw.flush(); // flushes the stream
    }
  }
}

That's all for this topic Java BufferedWriter Class With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Character Streams in Java IO
  2. Byte Streams in Java IO
  3. Write to a File in Java
  4. How to Append to a File in Java
  5. Reading File in Java Using Files.lines And Files.newBufferedReader

You may also like-

  1. How to Read File From The Last Line in Java
  2. Difference Between Thread And Process in Java
  3. LinkedHashSet in Java With Examples
  4. String Vs StringBuffer Vs StringBuilder in Java
  5. Constructor Overloading in Java
  6. Python Program to Display Fibonacci Series
  7. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  8. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

Saturday, November 19, 2022

Creating Temporary File in Java

Sometimes you may want to create temporary file in Java to store some data for the application. Once the job is done temp file can safely be discarded or you can delete it on exit. In this post we'll see how to create a temporary file in Java and how to read and write to temporary file.

In java.io.File class there are two methods for creating a temp file.

  • static File createTempFile(String prefix, String suffix, File directory)- Creates a new empty file in the specified directory, using the passed prefix and suffix strings to generate file name.
  • static File createTempFile(String prefix, String suffix)- Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

In java.nio.file.Files class also there are two methods for creating temporary files.

  • static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs)- Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. You can also pass an optional list of file attributes to set atomically when creating the file
  • static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs)- Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

Creating temporary file using java.io.File class methods

import java.io.File;
import java.io.IOException;

public class TempFile {

 public static void main(String[] args) {
  try {
   // Using default directory
   File tempFile = File.createTempFile("MyFile", ".temp");
   System.out.println("Temp file path- " + tempFile.getCanonicalPath());
   // Specifying directory
   File testFile = File.createTempFile("MyFile", ".temp", new File("F:\\Temp"));
   System.out.println("Temp file path- " + testFile.getCanonicalPath());
   
   tempFile.deleteOnExit();
   testFile.deleteOnExit();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
}

Output

Temp file path- C:\Users\netjs\AppData\Local\Temp\MyFile13999667283141733746.temp
Temp file path- F:\Temp\MyFile11668072031090823667.temp

Creating temporary file using java.nio.file.Files class methods

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class TempFile {

 public static void main(String[] args) {
  try {
   // Using default directory
   Path tempFile = Files.createTempFile("MyFile", ".temp");
   System.out.println("Temp file path- " + tempFile);
   // Specifying directory
   Path testFile = Files.createTempFile(Path.of("F:\\Temp"), "MyFile", ".temp");
   System.out.println("Temp file path- " + testFile);
   // Read write temp file operations
   
   // delete file on exit
   tempFile.toFile().deleteOnExit();
   testFile.toFile().deleteOnExit();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
}

Output

Temp file path- C:\Users\Anshu\AppData\Local\Temp\MyFile2647482374773079441.temp
Temp file path- F:\Temp\MyFile16822359990880283479.temp

Reading and writing temporary file in Java

Once the temporary file is created you will of course use it to write some data and read some data from the temp file. You can use BufferedWriter and BufferedReader for writing to and reading from a temp file.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class TempFile {

 public static void main(String[] args) {
  try {
   // Specifying directory
   File testFile = File.createTempFile("MyFile", ".temp", new File("F:\\Temp"));
   System.out.println("Temp file path- " + testFile.getCanonicalPath());
   testFile.deleteOnExit();
   // Writing to temp file
   BufferedWriter bw = new BufferedWriter(new FileWriter(testFile));
   bw.write("Writing to the temp file");
   bw.close();
   // Reading from temp file
   String str;
   BufferedReader br = new BufferedReader(new FileReader(testFile));
   while((str = br.readLine()) != null){
    System.out.println("Line is - " + str);
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
}

Output

Temp file path- F:\Temp\MyFile16468233438314323721.temp
Line is - Writing to the temp file

That's all for this topic Creating Temporary File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Buffered Streams in Java IO
  2. How to Create Password Protected Zip File in Java
  3. Compress And Decompress File Using GZIP Format in Java
  4. Reading File in Java Using Files.lines And Files.newBufferedReader
  5. How to Read File From The Last Line in Java

You may also like-

  1. LinkedBlockingDeque in Java
  2. Difference Between sleep And wait in Java Multi-Threading
  3. Functional Interfaces in Java
  4. Equality And Relational Operators in Java
  5. Type Wrapper Classes in Java
  6. Connection Pooling With Apache DBCP Spring Example
  7. Bean Definition Inheritance in Spring
  8. Input Splits in Hadoop

Friday, November 18, 2022

JSX in React

If you have started working on React you would have definitely heard about JSX. In this tutorial we'll learn what is JSX, how to use JSX and what are the rules about using JSX.


What is JSX

JSX is a syntax extension for JavaScript that lets you write HTML-like markup with in a JavaScript file. In React you can write code as given below which is a mix of both JS and HTML.

function helloWorld(){
  return <h2>HelloWorld from React</h2>
}

As per React documentation the React philosophy is not to separate technologies by putting markup and logic in separate files but to separate concerns by creating Components that contain both markup and logic in a single file.

Since JSX is not valid JavaScript so browsers can't read it directly. It has to be translated (using transpiler like Babel) into React.createElement() calls.

The function helloWorld as written above would be transpiled behind the scenes into following code.

function helloWorld() {
  return React.createElement("h2", null, "Hello World from React");
}

Actually, React doesn't require using JSX but writing your code as a series of React.createElement() functions would be quite tedious. JSX is more intuitive as you have both UI and JavaScript code at the same place. It also allows React to show more useful error and warning messages.

Rules of using JSX

  1. At the end it is all JavaScript and in JavaScript a function can return a single value so that applies to JSX too. You can only return a single root element from a component. To return multiple elements from a component, wrap them with a single parent tag.

    Below JSX code will give an error as you are trying to return multiple elements.

    function Hello() {
      return(
        <h2>Hello World from React</h2>
        <p>This is the React code</p>
      );
    }
    

    Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

    You can use <div> to wrap multiple elements.

    function Hello() {
        return(
        <div>
            <h2>Hello World from React</h2>
            <p>This is the React code</p>
        </div>
        );
    }
    

    If you don’t want to add an extra <div> to your markup, you can write <> and </> which is a shorter syntax for declaring fragments.

    function Hello() {
        return(
        <>
            <h2>Hello World from React</h2>
            <p>This is the React code</p>
        </>
        );
    }
    

    Or you can explicitly use React.Fragment which has to be imported.

    import { Fragment } from "react";
    
    export default function Hello() {
        return(
        <Fragment>
            <h2>Hello World from React</h2>
            <p>This is the React code</p>
        </Fragment>
        );
    }
    
  2. JSX requires all the tags to be explicitly closed. Even the line break tag (<br>) and horizontal rule tag (<hr>) must be closed <br />, <hr /> otherwise you will get an error.

    Parsing error: Unterminated JSX contents.

  3. User defined React component must be capitalized. An element with a lowercase letter is considered to be a built-in component like <h2> or <div> and results in a string 'h2' or 'div' passed to React.createElement. When the component name is capitalized like <Hello /> that compiles to React.createElement(Hello) and correspond to a component defined or imported in your JavaScript file. For example if you have a Hello.js file which is then used in App.js

    Hello.js

    export default function Hello() {
        return(
        <div>
            <h2>Hello World from React</h2>
            <p>This is the React code</p>
        </div>
        );
    }
    

    App.js

    import Hello from "./Components/Examples/HelloWorld";
    function App() {
      return (
        <Hello />
      );
    }
    export default App;
    
  4. Most of the JSX attributes are in camelCase. JSX is translated into JavaScript and attributes written in JSX become keys of JavaScript objects, as showed in the React.createElement() code used above. But JS has limitations in valid variable names where you can't use dash or a reserved word like class.

    Since class is a reserved word, in React you write className.

    <div className="Test">
    

Including JavaScript expressions in JSX

When you want to pass String attributes to JSX you will enclose those attributes in single quote or double quotes.

<div className="Test">

If you want to include JavaScript expressions in JSX you need to wrap them in curly braces. That helps in making your code dynamic.

export default function Hello() {
    const name = 'Robert';
    return(
    <div>
        <h2>Hello World from {name}</h2>
    </div>
    );
}

In the example you first declare a constant name and then embed it with curly braces inside the <h2> tag.

You can even embed a JS function call between curly braces.

export default function Hello() {
    const curDate = new Date();
    // JS function
    const formatDate = (date) => {
        return new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long' }).format(date);
    }
    // rendering logic
    return(
    <div>
        <h2>Hello World, current date and time is {formatDate(curDate)}</h2>
    </div>
    );
}

That's all for this topic JSX in React. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Creating a New React Project - create-react-app
  2. React HelloWorld App - First React App
  3. Access Modifiers in Java

You may also like-

  1. Angular Project Structure With File Description
  2. Lambda expressions in Java 8
  3. How HashMap internally works in Java

Thursday, November 17, 2022

Type Erasure in Java Generics

When generics was introduced in Java there was a requirement for it to be compatible with the existing code, written in previous versions, which of course was non-generic. That is why you can still add raw types, as example- List alist = new ArrayList();
This will give you warning for raw type but you can still have a non-generic list like this. Another thing that happens internally for compatibility is to replace all type parameters which is known as type erasure in Java generics


How type erasure works in Java

As mentioned above, during the type erasure process, the Java compiler erases all type parameters and replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.

The Java compiler applies type erasure in generics to-

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. Which means, if you have a unbounded type parameter that will be replaced by Object while compiling the code. If there is a bounded parameter that will be replaced by the provided bound.
    The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.

As example if you have the following generic class

 
public class GenType<T> {
  T obj;
  public T getObj() {
    return obj;
  }

  public void setObj(T obj) {
    this.obj = obj;
  }  
}

here type parameter T is unbounded, thus the Java compiler replaces it with Object, so your compiled class won’t have any type parameter

public class GenType {
  Object obj;
  public Object getObj() {
    return obj;
  }

  public void setObj(Object obj) {
    this.obj = obj;
  }
}

If your class were using a bounded parameter as below-

public class GenType<T extends Number> {
  T obj;
  public T getObj() {
    return obj;
  }

  public void setObj(T obj) {
    this.obj = obj;
  }   
}

Here it will be replaced by the bound i.e. Number

public class GenType {
  Number obj;
  public Number getObj() {
    return obj;
  }

  public void setObj(Number obj) {
    this.obj = obj;
  }  
}

Bridge methods in Java

When compiling a class or interface that extends a parameterized class or implements a parameterized interface, the compiler may need to create a synthetic method, called a bridge method, as part of the type erasure process. In order to get an idea what bridge methods are let’s see an example.

If we have the following two classes-

GenType

public class GenType<T> {
  T obj;
  public GenType(T obj) { 
    this.obj = obj; 
  }

  public void setObj(T obj) {
    this.obj = obj;
  }  
}

MyGen

 
public class MyGen extends GenType<Integer> {
  public MyGen(Integer num) { 
    super(num); 
  } 
  public void setObj(Integer data) {
    System.out.println(" In MyGen.setData");
    super.setObj(data);
  } 
}

Here note that MyGen class extends the GenType class which has the Integer parameter. After compilation and type erasure, type parameters will be removed from both the classes and these classes will look as follows-

 
public class GenType {
  Object obj;
  public GenType(Object obj) { 
    this.obj = obj; 
  }

  public void setObj(Object obj) {
    this.obj = obj;
  }
}
 
public class MyGen extends GenType {
  public MyGen(Integer num) { 
    super(num); 
  } 
  public void setObj(Integer num) {
    System.out.println(" In MyGen.setData");
    super.setObj(num);
  }
}

If you have noticed, after type erasure setObj() method signatures don’t match in GenType and MyGen classes. In GenType class it becomes setObj(Object obj) where as in MyGen it becomes setObj(Integer num).

Therefore, the MyGen setObj method does not override the GenType setObj method.

To solve this problem and preserve the polymorphism of generic types after type erasure, a Java compiler generates a bridge method to ensure that subtyping works as expected. For the MyGen class, the compiler generates the following bridge method for setObj:

 
public class MyGen extends GenType {
  public MyGen(Integer num) { 
    super(num); 
  } 

  // Bridge method generated by the compiler
  public void setObj(Object num) {
    setObj((Integer) num);
  }
  public void setObj(Integer num) {
    System.out.println(" In MyGen.setData");
    super.setObj(num);
  }
}

Here you can see a bridge method which has the same signature as the setObj method of the GenType class is inserted and it delegates to the actual setObj method.

Generics Ambiguity errors because of type erasure

Let’s say you have the following class where you are trying to have two overloaded methods (set) with different type parameters K and V respectively.

 
class GenClass<K, V>{
  private K key;
  private V value;
  public GenClass(K key, V value) {
    this.key = key;
    this.value = value;
  }

  public void set(K key){
    this.key = key;
  }

  public void set(V value){
    this.value = value;
  }

  public K getKey(){
    return key;
  }
  public V getValue(){
    return value;
  }
}

This class will give compilation error
Erasure of method set(K) is the same as another method in type GenClass<K,V>
Erasure of method set(V) is the same as another method in type GenClass<K,V>

Though you may think since K and V are two different parameters so its ok to write overloaded methods using these parameters as arguments. But there is no such compulsion that these two parameters will be different, at the time of creating objects you can provide same type for both the type parameters.

Also type erasure will replace the type parameter with Object in this case so both the methods will become-

 
public void set(Object key){
 this.key = key;
}
 
public void set(Object value){
 this.value = value;
}

In a case like this it is better to give different name for the methods and avoid any ambiguity.

That's all for this topic Type Erasure in Java Generics. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Generics in Java
  2. Bounded Type Parameter in Java Generics
  3. Wildcard in Java Generics
  4. Enum Type in Java
  5. Spliterator in Java

You may also like-

  1. Varargs (Variable-length Arguments) in Java
  2. Java Stream API Tutorial
  3. Effectively Final in Java 8
  4. Java ThreadLocal Class With Examples
  5. Is String Thread Safe in Java
  6. Java ReentrantLock With Examples
  7. Java Collections Interview Questions And Answers
  8. Dependency Injection in Spring Framework

Wednesday, November 16, 2022

Creating a New React Project - create-react-app

In this tutorial you'll see how to create a new React project using create-react-app. As per React recommendation if you're learning React or creating a new single-page app, Create React App is the best way to go with it.

Prerequisite for using Create React App

You should have Nodejs (greater than version 14) installed in your system in order to use Create React App environment.

Check this post- How to Install Node.js and NPM in Windows to understand how to download and install NodeJS and NPM (Node Package Manager).

Create React App for Creating React project

If you want to create a React project named myreact-app go to the folder where you want to create this project and run the following command.

npx create-react-app myreact-app

It'll ask for permission to install the create-react-app packages, enter 'y'

Need to install the following packages:
create-react-app
Ok to proceed? (y) y

npx is a package runner tool that comes with npm, that's why NodeJS should be installed in your system.

Wait for the creation of project structure. Once all the packages are installed, initial React project structure as created by create-react-app should look like as given below.

React Project Structure

Running default app

Once project is created change directory to the created project folder.

cd myreact-app

Then run following command to run the app in development mode. This command compiles the app and start the development server.

npm start

If there is no error then it should automatically run the application in your browser or once you see the application is successfully compiled open the browser and type URL- http://localhost:3000/ to see the default application.

Under the hood, create-react-app uses Babel (JavaScript compiler) and webpack (combines every module your project needs into one or more bundles).

Want to create your first React app, check this post- React HelloWorld App - First React App

That's all for this topic Creating a New React Project - create-react-app. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JSX in React

You may also like-

  1. Angular Project Structure With File Description
  2. Lambda expressions in Java 8
  3. How HashMap internally works in Java

Tuesday, November 15, 2022

Convert String to float in Python

In this post we’ll see how to convert String to float in Python.

If you have a float represented as String literal then you need to convert it to float value if you have to use it in any arithmetic operation.

For example-

num1 = "50.56"
num2 = 20.45
result = num1 + num2
print("Sum is-", result)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 14, in <module>
    result = num1 + num2
TypeError: can only concatenate str (not "float") to str

As you can see num1 variable is of type string so Python tries to concatenate num2 to num1 rather than adding them. In such scenario you need to convert string to float.

Python program - convert String to float

To convert a Python String to a float pass that String to float() function which returns a float object constructed from the passed string.

num1 = "50.56"
num2 = 20.45
result = float(num1) + num2
print("Sum is-", result)

Output

Sum is- 71.01

ValueError while conversion

If the string doesn’t represent a valid number that can be converted to float, ValueError is raised. If you are not sure about the passed number it is better to use try and except for exception handling.

For example in the following Python function string ‘abc’ is passed as one of the argument value which results in ValueErorr being raised while converting it.

def add(num1, num2):
  try:
    result = float(num1) + float(num2)
    print("Sum is-", result)
  except ValueError as error:
    print('Error while conversion:', error)

add('abc', 10)

Output

Error while conversion: could not convert string to float: 'abc'

Getting integer part of the decimal number

If there is a decimal number stored as a string and you want only the integer part then directly using int() function results in error. You have to first convert string to float and then to int.

num = "50.56"
# Causes error
int_num = int(num) 
print("Integer part is-", int_num)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 10, in <module>
    int_num = int(num)
ValueError: invalid literal for int() with base 10: '50.56'

Correct way

num = "50.56"
int_num = int(float(num))
print("Integer part is-", int_num)

Output

Integer part is- 50

That's all for this topic Convert String to float in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Convert String to int in Python
  2. Python Program to Count Number of Words in a String
  3. Python String isnumeric() Method
  4. Operator Overloading in Python
  5. Check String Empty or Not in Python

You may also like-

  1. Name Mangling in Python
  2. Magic Methods in Python With Examples
  3. Passing Object of The Class as Parameter in Python
  4. Inheritance in Python
  5. Convert String to float in Java
  6. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  7. intern() Method in Java String
  8. Java Exception Handling Tutorial