Professional Documents
Culture Documents
React Chap-2
React Chap-2
Introduction:-
What is ReactJS?
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.
1
Move inside the same folder using the below command:
cd newfolder (your folder 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)
function App() {
return (
<h1> Hello World! </h1>
);
}
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:
Folder Structure
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/
contexts/
4
features/
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/
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/
pages/
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/
types/
utils/
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.
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.
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>;
}
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.
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.
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.
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 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
Main.js
12
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
React State
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.
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;
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
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
ReactDOM.render(<App/>, document.getElementById('app'));
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
To use a method as a props all the steps are described below order wise:
ParentCompnent.js:
import React, { Component } from 'react';
</div>
)
}
}
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:
this.state = {
parentName:'Parent'
}
this.greetParent = this.greetParent.bind(this)
}
greetParent() {
alert(`Hello ${this.state.parentName}`)
}
render() {
return (
<div>
17
</div>
)
}
}
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>
);
}
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:
function ChildComponent(props) {
return (
<div>
<button onClick={() => props.greetHandler()}>
Greet Parent
</button>
</div>
)
}
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>
)
}
}
20
.
21