Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Unit 2 Introduction to JSX & REACT JS

Introduction:-
 What is ReactJS?

ReactJS is a declarative, efficient, and flexible JavaScript library for


building reusable UI components. It is an open-source, component-based
front end library which is responsible only for the view layer of the
application. It was initially developed and maintained by Facebook and
later used in its products like WhatsApp & Instagram.

The main objective of ReactJS is to develop User Interfaces (UI) that


improves the speed of the apps. It uses virtual DOM (JavaScript object),
which improves the performance of the app. The JavaScript virtual DOM
is faster than the regular DOM. We can use ReactJS on the client and
server-side as well as with other frameworks. It uses component and data
patterns that improve readability and helps to maintain larger apps.

 Installation or Setup.

Step 1: Install Node.js installer for windows. Click on this link. Here
install the LTS version (the one present on the left). Once
downloaded open NodeJS without disturbing other settings, click
on the Next button until it’s completely installed.

Step 2: Open command prompt to check whether it is completely


installed or not type the command –>
node -v
Step 3: Now in the terminal run the below command:
npm install -g create-react-app
It will globally install react app for you. To check everything went
well run the command
create-react-app --version
Step 4:Now Create a new folder where you want to make your
react app using the below command:
mkdir newfolder

1
Move inside the same folder using the below command:
cd newfolder (your folder name)

Step 5: Now inside this folder run the command –>


create-react-app reactfirst YOUR_APP_NAME

Step 6: Now open the IDE of your choice for eg. Visual studio code
and open the folder where you have installed the react
app newfolder (in the above example) inside the folder you will
see your app’s name reactapp (In our example). Use the terminal
and move inside your app name folder.Use command cd
reactapp (your app name)

Step 7: To start your app run the below command :


npm start

 Hello World Program

import React from 'react';


import './App.css';

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

export default App;

 Creat a First app

Create React App is a comfortable environment for learning React, and is


the best way to start building a new single-page application in React.
It sets up your development environment so that you can use the latest
JavaScript features, provides a nice developer experience, and optimizes

2
your app for production. You’ll need to have Node >= 14.0.0 and npm >=
5.6 on your machine. To create a project, run:

npx create-react-app my-app


cd my-app
npm start

 Folder Structure

Composability allows you to reuse code between components. This is a very


powerful concept in React, and a large influence as to why it’s common to break-out and
group reusable code.

Local first. When building components it’s best to keep the code that pertains only to that
component, local. In our example above, the authentication Feature Component contains

3
an auth-form component, and some utils. Instead of breaking those out into their
respective components or utils directory, we keep them local because the code they
contain will never be used in another component. This will help prevent those directories
from becoming unreasonably large as the project scales.

 Flatter is better. Every time you nest you’re adding to the mental model required to grok
a component’s local code. Nesting also comes with other pain points, so it’s best to avoid
too much nesting.

 Nest as you grow. Flatter may be better, but there are reasons to nest. For example if
your Features directory grows too large, you might want to group your features by
something logical.

components/

 Contains reusable components that are most often used to compose Feature or Page
components.

 These components are almost always pure and presentational, with no side-effects.

constants/

 Contains reusable & immutable strings like URLs or Regex Patterns.

 A single index file will suffice for most projects.

contexts/

 Contains reusable contexts used to provide data through a tree of components.

 If using Redux this directly is likely not needed.

4
features/

 Contains reusable Feature Components. A Feature Component is a concept inspired by


Redux in which all logic required for a feature is colocated to a single directory. A Feature
Component is often composed of many other components, either local or shared. The
same is true for all resources: utils, types, hooks, and so on.

 Feature Components often include side-effects.

 If using Redux, and interacts with the Store, the Feature Component will include a slice file
that defines the “slice” of the Redux Store the feature represents.

layouts/

 Contains reusable Layout Components. A Layout Component is a component that


composes the layout of a page. It will often import components such as app-bar, app-
footer, app-side-nav.

 If your project is likely to only have a single layout, this directory might not be necessary,
and the Layout Component can live in the components directory.

hooks/

 Contains reusable React Hooks.

pages/

 Contains Page Components. Each Page Component is associated with a route.

 Page Components compose the content of a page by importing Components and Feature
Components.

 A Page Component should rarely include side-effects, and should instead delegate side-
effects to Feature Components.

5
services/

 Contains reusable code for interacting with an API, often in the form of hooks, and ideally
utilizing a server-cache tool like React Query or RTK Query.

 Do not mistake this with an Angular-esque service which is meant to handle injecting
functionality into components. React handles this scenario using contexts and hooks. This
directory should only contain code for interacting with an API.

 Inspired by RTK Query’s recommendation to keep your API definition in a central location.
This is the only example of where we purposely break the local-first rule. I like to think of
API definitions as their own modular feature. In fact it’s not uncommon to have
a features/api directory in lieu of a services directory.

styles/

 Reusable or global styles.

 Might include configurations, resets, or variables.

types/

 Reusable types for projects utilizing TypeScript or Flow.

utils/

 Reusable utility functions.

 These functions should always be pure and produce no side-effects.

6
store.ts

 If using Redux, this file is where you import all of your slices and configure your Redux
Store.

Pro Tips

 Read official documentations every time you start a new project. You never know what
new tool a library may have added since you last implemented it.

 Stop using PascalCase for file names. Instead use kebab-case for all files.

 Use a server-state tool like React Query or Redux Toolkit Query.

 Use a component library like MUI.

 Use a hook library like usehooks-ts for common hooks.

 Component:-
A Component is considered as the core building blocks of a React application. It
makes the task of building UIs much easier. Each component exists in the same
space, but they work independently from one another and merge all in a parent
component, which will be the final UI of your application.

Every React component have their own structure, methods as well as APIs. They
can be reusable as per your need. For better understanding, consider the entire
UI as a tree. Here, the root is the starting component, and each of the other
pieces becomes branches, which are further divided into sub-branches.

n ReactJS, we have mainly two types of components. They are

7
 Functional component

In React, function components are a way to write components that only contain a
render method and don't have their own state. They are simply JavaScript functions
that may or may not receive data as parameters. We can create a function that takes
props(properties) as input and returns what should be rendered. A valid functional
component can be shown in the below example.

function WelcomeMessage(props) {
return <h1>Welcome to the , {props.name}</h1>;
}

The functional component is also known as a stateless component because they do


not hold or manage state. It can be explained in the below example.

Example
import React, { Component } from 'react';
class App extends React.Component {
render() {
return (
<div>
<First/>
<Second/>
</div>
);
}
}
class First extends React.Component {
render() {
return (
<div>
<h1>JavaTpoint</h1>
</div>
);
}
}
class Second extends React.Component {
render() {

8
return (
<div>
<h2>www.javatpoint.com</h2>
<p>This websites contains the great CS tutorial.</p>
</div>
);
}
}
export default App;

 Class component

Class components are more complex than functional components. It requires you to extend
from React. Component and create a render function which returns a React element. You can
pass data from one class to other class components. You can create a class by defining a class
that extends Component and has a render function. Valid class component is shown in the
below example.

class MyComponent extends React.Component {


render() {
return (
<div>This is main component.</div>
);
}
}

Example
In this example, we are creating the list of unordered elements, where we will
dynamically insert StudentName for every object from the data array. Here, we are
using ES6 arrow syntax (=>) which looks much cleaner than the old JavaScript syntax.
It helps us to create our elements with fewer lines of code. It is especially useful when
we need to create a list with a lot of items.

import React, { Component } from 'react';


class App extends React.Component {
constructor() {
super();
this.state = {
data:

9
[
{
"name":"Abhishek"
},
{
"name":"Saharsh"
},
{
"name":"Ajay"
}
]
}
}
render() {
return (
<div>
<StudentName/>
<ul>
{this.state.data.map((item) => <List data = {item} />)}
</ul>
</div>
);
}
}
class StudentName extends React.Component {
render() {
return (
<div>
<h1>Student Name Detail</h1>
</div>
);
}
}
class List extends React.Component {
render() {
return (
<ul>

10
<li>{this.props.data.name}</li>
</ul>
);
}
}
export default App;

 Introduction to JSX:-
JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree
structures) in the same file where you write JavaScript code, then
preprocessor will transform these expressions into actual JavaScript code.
Just like XML/HTML, JSX tags have a tag name, attributes, and children.

o It is faster than regular JavaScript because it performs optimization while


translating the code to JavaScript.
o Instead of separating technologies by putting markup and logic in
separate files, React uses components that contain both. We will learn
components in a further section.
o It is type-safe, and most of the errors can be found at compilation time.
o It makes easier to create templates.

Example
import React, { Component } from 'react';
class App extends Component{
render(){
return(
<div>
<h1>JavaTpoint</h1>
<h2>Training Institutes</h2>
<p data-demoAttribute = "demo">This website contains the best CS tutorials.</p>
</div>
);
}
}
export default App;

11
Props:-
 ReactJS Props

Props stand for "Properties." They are read-only components. It is an object


which stores the value of attributes of a tag and work similar to the HTML
attributes. It gives a way to pass data from one component to other
components. It is similar to function arguments. Props are passed to the
component in the same way as arguments passed in a function.

Props are immutable so we cannot modify the props from inside the
component. Inside the components, we can add attributes called props.
These attributes are available in the component as this.props and can be
used to render dynamic data in our render method.

When you need immutable data in the component, you have to add props
to reactDom.render() method in the main.js file of your ReactJS project and
used it inside the component in which you need. It can be explained in the
below example.

Example

App.js

import React, { Component } from 'react';


class App extends React.Component {
render() {
return (
<div>
<h1> Welcome to { this.props.name } </h1>
<p> <h4> hello world </h4> </p>
</div>
);
}
}
export default App;

Main.js

12
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';

ReactDOM.render(<App name = "svcollege!!" />, document.getElementById('app'));

 React State

The state is an updatable structure that is used to contain data or information


about the component. The state in a component can change over time. The
change in state over time can happen as a response to user action or system
event. A component with the state is known as stateful components. It is the
heart of the react component which determines the behavior of the
component and how it will render. They are also responsible for making a
component dynamic and interactive.

A state must be kept as simple as possible. It can be set by using


the setState() method and calling setState() method triggers UI updates. A
state represents the component's local state or information. It can only be
accessed or modified inside the component or by the component directly. To
set an initial state before any interaction occurs, we need to use
the getInitialState() method.

For example, if we have five components that need data or information from
the state, then we need to create one container component that will keep
the state for all of them.

Example
The below sample code shows how we can create a stateful component using ES6
syntax.

import React, { Component } from 'react';


class App extends React.Component {
constructor() {
super();
this.state = { displayBio: true };
}
render() {

13
const bio = this.state.displayBio ? (
<div>
<p><h3>good morning all of you.</h3></p>
</div>
) : null;
return (
<div>
<h1> Welcome to my home!! </h1>
{ bio }
</div>
);
}
}
export default App;

 Destructing Props and State

It is possible to combine both state and props in your app. You can set the state in the
parent component and pass it in the child component using props. It can be shown in the
below example.

Example
App.js

import React, { Component } from 'react';


class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "JavaTpoint",
}
}
render() {
return (
<div>
<JTP jtpProp = {this.state.name}/>
</div>
);

14
}
}
class JTP extends React.Component {
render() {
return (
<div>
<h1>State & Props Example</h1>
<h3>Welcome to {this.props.jtpProp}</h3>
<p>my world</ p>
</div>
);
}
}
export default App;

Main.js

import React from 'react';


import ReactDOM from 'react-dom';
import App from './App.js';

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

 setState

The state of a component can change either due to a response to an


action performed by the user or an event triggered by the system.
Whenever the state changes, React re-renders the component to the
browser. Before updating the value of the state, we need to build an
initial state setup. Once we are done with it, we use the setState()
method to change the state object. It ensures that the component has
been updated and calls for re-rendering of the component.

setState is asynchronous call means if synchronous call get called it may


not get updated at right time like to know current value of object after
update using setState it may not get give current updated value on
console. To get some behavior of synchronous need to pass function
instead of object to setState.

15
Syntax: We can use setState() to change the state of the component
directly as well as through an arrow function.
set // OR
setState((prevState) => ({
stateName: prevState.stateName + 1
}))
State({ stateName : updatedStateValue })

 methods as Props

ReactJS is a front-end JavaScript library for building user interfaces written


and maintained by Facebook. We know that everything in ReactJS is
a component and to pass in data to these components, props are used.
Although passing in props like this is great, it surely lacks flexibility in an
application. For example, we cannot let the child communicate with the
parent in this way. This, nonetheless, can be done by passing methods as
props in ReactJS.

To use a method as a props all the steps are described below order wise:

Step 1: To do this let’s make a new component


named ParentComponent.js. Now let’s make the basic layout for a class
component in this file.

ParentCompnent.js:
import React, { Component } from 'react';

class ParentComponent extends Component {


render() {
return (
<div>

</div>
)
}
}

export default ParentComponent;

16
Step 2: Now let’s set a state to greet our parent whenever this component
is rendered, setting a state is not necessary, but we will do it just to make
an application more dynamic. Also, let’s make an event that gives an alert
whenever the parent component is rendered. Do not forget to bind the
event so that the this keyword won’t return “undefined“.
ParentComponent.js:

import React, { Component } from 'react';

class ParentComponent extends Component {


constructor(props) {
super(props)

this.state = {
parentName:'Parent'
}

this.greetParent = this.greetParent.bind(this)
}

greetParent() {
alert(`Hello ${this.state.parentName}`)
}

render() {
return (
<div>

17
</div>
)
}
}

export default ParentComponent;


Step 3: Let’s not forget to import this into our App.js file.
App.js:

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

// imports component
import ParentComponent from './components/ParentComponent';

function App() {
return (
<div className="App">
<h1>-----------METHODS AS PROPS-------------</h1>
<ParentComponent />

</div>
);
}

export default App;

18
Step 4: Now let’s make a new component. Let’s call
this ChildComponent.js, and make a simple functional component. Let’s
make a simple button, and then pass the method greetParent() as a
property. Essentially, the button must greet the parent when it is clicked.
ChildComponent.js:

import React from 'react';

function ChildComponent(props) {
return (
<div>
<button onClick={() => props.greetHandler()}>
Greet Parent
</button>
</div>
)
}

export default ChildComponent;

Ste 5: Don’t forget to import the ChildComponent in ParentComponent. So


the final code for ParentComponent will be as follows.
ParentComponent.js:

import React, { Component } from 'react';


import ChildComponent from './ChildComponent';

class ParentComponent extends Component {

19
constructor(props) {
super(props);

this.state = {
parentName:'Parent'
}

this.greetParent = this.greetParent.bind(this)
}

greetParent() {
alert(`Hello ${this.state.parentName}`)
}

render() {
return (
<div>
<ChildComponent greetHandler={this.greetParent}/>
</div>
)
}
}

export default ParentComponent;

20
.

21

You might also like