Getting Started with ReactJS
Harsh Mishra
Posted on April 29, 2020
The recent buzzword that has caught the attention of many Front-End Developers across the Javascript Ecosystem has been the word "React". Ever since, it was launched by Facebook as a "declarative, efficient, and flexible JavaScript library for building user interfaces", React has got huge traction among Developers to build intuitive User-Interface with minimal code compared to the Vanilla Javascript or JQuery that was utilized prior to the rise of niche Front-End Development Frameworks.
According to a post by Tecla, React has been the leading framework in terms of usage and popularity compared to other Front-End Frameworks like Angular and Vue. In this article, we will be covering what is React, how can we develop Applications with React, and in the end, we will be putting all our knowledge to build a Simple Interest Application.
First things, first! What is React?
React is a Javascript library developed by Facebook, which allows you to create attractive User-Interface and is one of the most influential and popular Javascript libraries since it first appeared on the scene. In the first half of the article, we will be setting up our environment and create a "Hello, React!" Application using Node as a Server Setup.
So, let's get started with React and make our first application using React while exploring concepts in the midst!
1. Install Node.js:
Before we start with React, it is absolutely necessary to have our Node.js
Installation. You can download Node.js here, either by a Binary Package or a
Pre-Built Installer. Once downloaded, you can verify if the Node.js
Environment has been set up by running the following commands:
$ node -v
$ npm -v
2. Install create-react-app:
Once you have the Versions checked and verified, move onto the next command: create-react-app. This will install the React using NPM. You don't need to worry about the complexity of the React as a whole. This Package will take care of that!
$ npm install -g create-react-app
If you are using Yarn for any sort of reason, you can install create-react-app globally by using the following command:
$ yarn global add create-react-app
3. Verify that the Package has been Installed:
Let us verify if our create-react-app is running fit and fine, by running the following command:
$ create-react-app --version
4. Create a Hello-World App:
You can create a new React App by using the create-react-app command. Here I will be using Hello, React! as the name of my application. So push in the following command, to kick-start your new application:
$ create-react-app hello-react
After a lot of output and installations, your React App will be initialized. cd into your newly created folder and you can take a look at all the files present in your React Application.
$ cd hello-react
Your React App creates folders and subfolders. Open the src folder, and take a look at the files present in there. This is where we will be working first before we move onto the next steps. Open App.js and you can see the following block of code present there:
Open App.js and you can see the following block of code present there:
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>
);
}
Understanding the Components
- What is React Components? React Components is a Component that takes in parameters called properties (or 'props') and returns a list of views in a hierarchical manner using the render method.
- What is the Render Method? 'Render' method allows you to view all the things you wanna see on the screen. React Developers use JSX which is something like HTML and Javascript but it allows Developers to write React Elements in the form of Javascript Objects, which can be used throughout the program.
- What is JSX? JSX is a Syntax Extension to Javascript and it produces React Elements.
With this knowledge in our minds, let's get started!
Creating a Hello World Application
- Writing the Code
Delete the Block of Code we have mentioned in the previous point and let's write our new code.
class App extends React.Component {
render() {
return (
<h1>Hello React</h1>
);
}
}
Let's understand Class Components versus Functional Components. A functional component is just a plain JavaScript function that accepts props as an argument and returns a React element. A Class Component, on the other hand, requires you to extend from React.Component and create a render function that returns a React element.
Let's define a Functional Component, instead of a Class Component, and explore some of its advantages. You can write the following block of code by replacing the older one:
function App(){
const element=(
<div>
<h1>Hello, React!</h1>
</div>
);
return element;
}
What makes Functional Component, better?
- Improves Readibility and Usability.
- Easier to Test and Reusable.
Let's kick-start the code and render it on our Browser. Push in the command:
npm start
The React App will now be rendered on the Local Host on Port 3000. You can now freely experiment with your Application. You have finally created
your first React Application!
Building a Simple Interest Application
So, you have developed your Hello, React! Application. Cool! Want to get your hands dirty, with more code. You are the right place! We will build a Simple Interest Calculator in this second part of the article, to explore various React functionality and concepts and get digging deeper with the code. To properly follow this, I hope you have already installed Node and create-react-app because we will be using them to bootstrap our project and get started.
- Kickstarting the Application
Open your Command Line Interface/Shell, and push in the following command:
$ create-react-app simple-interest
We are naming our application, Simple Interest here, where we can give a Principal Amount, Rate of Interest, and finally the Time for which the amount has been given for loan, and our React Application has to calculate the Simple Interest Amount. We will be using JSX here without much styling, so it will be a very basic application to get our things done!
After a long series of outputs, I hope that your Application has been initialized. cd into your newly created folder and you can take a look at all the files present in your React Application.
$ cd simple-interest
- Exploring the Code
Your React App creates folders and subfolders. Open the src folder, and take a look at the files present in there. This is where we will be working first before we move onto the next step. We will be writing some of our own code here, so it is preferred to delete the earlier block of code present in App.js and start afresh.
- Designing the Workflow of the Application
We have got four variables in our project: Principal, Time, Rate, and Simple Interest Calculated. We will be using them in multiple places, so we will alias them using Flow via a Type Alias. So, let us define a block of code where we will use a Type Alias to define our variables which we will be using in our code.
type State = {
data: {
principle: number,
time: number,
rate: number
},
interest: number
};
What exactly is a Type Alias?
Type aliases are created using the keyword type followed by its name, an equals sign =, and a type definition. It allows us to define our variables which we can call multiple times in the code. With this knowledge in mind, let's move onto the next block of code.
- Writing the Code
Let us now define, a Class Component and define a Constructor which can initialize our variables defined in the Type Alias. The constructor is a method used to initialize an object's state in a class. It automatically called during the creation of an object in a class.
When you implement the constructor for a React component, you need to call the super(props) method before any other statement. If you do not call the super(props) method, this.props will be undefined in the constructor and can lead to bugs.
constructor(){
super()
this.state= {
data: {
principle: 0,
time: 0,
rate: 0
},
interest: 0
}
}
By using Constructors, we are initializing the local state of the component by assigning an object to this.state and it is used for binding event handler methods that occur in your component.
Let us now define a function that can calculate the Simple Interest by using the formula: Simple Interest=Principal*Time*Rate. We will define a function for our need:
calculate_interest(){
let p = this.state.data.principle;
let t = this.state.data.time;
let r = this.state.data.rate;
let interest_calculated = (p * t * r)/100;
console.log(interest_calculated)
this.setState({interest: interest_calculated})
}
You can read more about React State here but what is this? Basically ‘this’ keyword references a JavaScript element depending on the scope or context of its use. In React we use components that are classes that derived from React.Component. Many times we invoke functions from the component’s controllers that need data either from the component’s props or state by using this.props or this.state.
- Rendering the Code
We will now use Synthetic Wrapper, a cross-browser wrapper around the browser’s native event for Event Handling. Let us define a
handleInput()
where we use HTMLButtonElement as an Event Handler to access your button instance use event.currentTarget
.
handleInput(attribute: string, event: SyntheticEvent<HTMLButtonElement>){
let context = attribute;
let input = this.state.data;
let value = event.currentTarget.value;
input[context] = value;
this.setState({
data: input
})
To get the element instance, like HTMLButtonElement in the example above, it is a common mistake to use event.target instead of event.currentTarget. We have now finally defined, everything that we are going to need to perform the Operations. Now, we will write some code to render some JSX Code to finally kick-start the Application on the Client Side. Let's take a look at the code that we have implemented till now:
type State = {
data: {
principle: number,
time: number,
rate: number
},
interest: number
};
class App extends Component<State> {
constructor(){
super()
this.state= {
data: {
principle: 0,
time: 0,
rate: 0
},
interest: 0
}
}
calculate_interest(){
let p = this.state.data.principle;
let t = this.state.data.time;
let r = this.state.data.rate;
let interest_calculated = (p * t * r)/100;
console.log(interest_calculated)
this.setState({interest: interest_calculated})
}
handleInput(attribute: string, event: SyntheticEvent<HTMLButtonElement>){
let context = attribute;
let input = this.state.data;
let value = event.currentTarget.value;
input[context] = value;
this.setState({
data: input
})
}
Let's use Render to render the React Element in the DOM. We will define the JSX Tags and Elements to render a Client-Side
Operation. The Code is Self-Explanatory and you can very well experiment with it.
render() {
return (
<div>
<div className="calculator-container">
<div>
<label>principle</label>
<input type="number" name="principle" placeholder="principle" onChange={this.handleInput.bind(this, 'principle')}/>
</div>
<div>
<label>time</label>
<input type="number" name="time" placeholder="time" onChange={this.handleInput.bind(this, 'time')}/>
</div>
<div>
<label>rate</label>
<input type="number" name="rate" placeholder="rate" onChange={this.handleInput.bind(this, 'rate')}/>
</div>
<button type="submit" onClick={this.calculate_interest.bind(this)}> Calculate </button>
<div>Interest: {this.state.interest}</div>
</div>
</div>
);
}
Here we are using the Bind Function, but what is it actually? Every Javascript object has three built-in methods that can change the ‘this’ context for a function. The first two, .call() and .apply() are similar in that the first argument you pass to them is the new context and then you can pass them individual arguments or an array respectively. The .bind() method is similar to the other two in that you pass it the context you want to bind the function to, but it does not immediately run the function. Instead a copy of the function with the switched context is returned.
Let's kick-start the code and render it on our Browser. Push in the command:
$ npm start
The React App will now be rendered on the Local Host on Port 3000. You can now freely experiment with your Application. You have finally created your Simple Interest React Application!
Now we have developed our first React Application, let us know have a look at what advantages does React provides over traditional Web Development Frameworks?
Easy to Implement: React has been remarked to have a gentle learning curve and is easy to implement and customize. With a unidirectional data-flow and the feature to break the entire code into components, React is a one-way solution to develop intuitive User-Interfaces.
Fast Rendering and SEO-Friendly: React has been known to have Fast Rendering and Websites developed with React are SEO (Search Engine Optimization) Friendly.
Quick Rendering with Virtual DOM: Perhaps the most earmarked feature of React is Virtual DOM which enables the creation of scalable web applications. Code Stability is another feature that comes with React which makes it developer-friendly and also easy to customize and enhance.
Posted on April 29, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024