0% found this document useful (0 votes)
17 views54 pages

Java Spring AWS & React Training Guide

The document provides a comprehensive training guide on Java Spring and AWS, focusing on React as a JavaScript library for building user interfaces. It covers key concepts such as component-based architecture, state management, lifecycle methods, and the use of React Router for navigation. Additionally, it introduces Node.js and NPM, along with practical examples and best practices for developing applications using React.

Uploaded by

rohit47474
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views54 pages

Java Spring AWS & React Training Guide

The document provides a comprehensive training guide on Java Spring and AWS, focusing on React as a JavaScript library for building user interfaces. It covers key concepts such as component-based architecture, state management, lifecycle methods, and the use of React Router for navigation. Additionally, it introduces Node.js and NPM, along with practical examples and best practices for developing applications using React.

Uploaded by

rohit47474
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Java Spring AWS Training

Authorized & published by TEKBasic LLC


REACT
• Introduction to REACT
Introduction to state management
• Understanding the principles of REACT
React Context API
• Introduction to Virtual DOM Redux for state management
• Setting up development environment ([Link], npm, Middleware and async actions
create-react-app) Forms/Form Validation and router
React Router
• Creating and rendering components
Nested routing
• JSX syntax and its benefits Programmatic navigation
• REACT component Handling route parameters
Controlled vs. uncontrolled components
• Understanding component-based architecture Form handling in REACT
• State and props Form validation techniques
• Handling events Using libraries like Form or React Hook Form
REST API Integration
• Lifecycle methods Fetch API
• Conditional rendering and lists Axios for HTTP requests
Consuming REST APIs in REACT
• Managing State
Handling loading and error states
INTRODUCTION TO REACT

Same code in [Link], [Link] , [Link]

- Same code is repeated multiple times in multiple pages

- To load the application content/result takes time.

- Loading time is more for high animation pages.

- Calls DOM Elements Every time while page Loading is going on.

- Anyone can see the source code from view page source.

- Write the code from scratch for mobile App development.


React is a popular JavaScript library for building user interfaces, particularly single-page applications where you need a fast,
interactive user experience. Here are some key points about React:
1. Component-Based Architecture
Components: React applications are built using components, which are independent, reusable pieces of code that define a
part of the user interface. Components can be either class-based or functional.
Props and State: Props (properties) are inputs to components, and state is an internal data store (object) that can change
over time.
2. JSX Syntax
JSX: JavaScript XML (JSX) is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files.
It makes it easier to visualize the structure of the UI components.
3. Virtual DOM
Virtual DOM: React uses a virtual DOM to improve performance. When a component's state changes, React creates a virtual
representation of the DOM and compares it to the real DOM. It then updates only the parts of the DOM that changed.
4. Lifecycle Methods
Lifecycle Methods: In class-based components, there are lifecycle methods that allow you to hook into different phases of a
component’s life (e.g., mounting, updating, unmounting).
5. Hooks
Hooks: Introduced in React 16.8, hooks allow you to use state and other React features in functional components. Common
hooks include useState, useEffect, and useContext.
6. React Router
React Router: A library for managing navigation and routing in React applications. It allows you to build a single-page application
with navigation.
7. State Management
State Management: Besides component-level state, for larger applications, you might use state management libraries like Redux,
Context API, or MobX.
8. Ecosystem
Ecosystem: React has a rich ecosystem with numerous libraries and tools that integrate well with it, such as Create React App
(for bootstrapping projects), [Link] (for server-side rendering), and more.
SINGLE PAGE APPLICATION
- Root page of the project - [Link] [Single page Application].
- Re-use The code for Multiple times without repetition
- Reduces time to load application content/result
- VIRTUAL DOM
- No one can see the code from View page source
- Reactive Native is used for mobile development which is the extension of react.
- Mobile APP= 20%[Reactive Native]+[80% React ]
Getting Started
• To start with React, you can use Create React App, a CLI tool that sets up a
new React project with a good default configuration
• npx create-react-app my-app
• cd my-app
• npm start
NODE JS

[Link]:
[Link] is an open-source, cross-platform, JavaScript runtime environment
that executes JavaScript code outside of a web browser.
Node. js is not a framework, its only a runtime environment
to run JavaScript on server-side. Node. js, as a package,
contains an interpreter and a compiler.
Download :[Link]
NPM
NPM:
The npm (Node Package Manager), is standard command line tool to install [Link]
dependencies, and also a public database of JavaScript packages available for download.

[Link] uses a package manager[NPM], where you can find and install thousands of packages.

A package is a directory with one or more modules inside of it and a [Link] file which has
metadata about the package.
JSX

JSX stands for JavaScript XML.


JSX allows us to write HTML in React.
JSX makes it easier to write and add HTML in React.
Coding JSX
JSX allows us to write HTML elements in JavaScript and place them in the DOM
without any createElement() and/or appendChild() methods.
JSX converts HTML tags into react elements.
Example
Coding without jsx:
const example = [Link]('h1', {}, 'I do not use JSX!’);
const root = [Link]([Link]('root'));
[Link](example);

Coding with jsx:


const example= <h1>This is an JSX example</h1>;
const root = [Link]([Link]('root'));
[Link](example);
Component

In React, a component is the fundamental building block of a React application.


Components can be class-based or functional, and they allow you to break down
the UI into reusable pieces.
Types of Components
1. Functional Components: These are simpler and are declared as JavaScript
functions. They can accept props and return React elements.
Example:
import React from 'react';
function Greeting(props) {
return <h1>Hello, {[Link]}!</h1>;
}
export default Greeting;
2. CLASS COMPONENT:
When creating a React component, the component's name MUST start with an upper case letter.
A class component must include the extends [Link] statement. This statement creates an inheritance
to [Link], and gives your component access to [Link]'s functions.
The component also requires a render() method, this method returns only one HTML tag we can't return multiple
html tags. to return multiple html tags we use fragment tags.

class Car extends [Link] {


render() {
return <h2>Hi, I am a Car</h2>;
}
}
const root = [Link]([Link]('root'));
[Link](<Car/>);
Props

Components can be passed as props, which stands for properties.


Props are like function arguments, and you send them into the component as
attributes.
Example
Use an attribute to pass a color to the Car component, and use it in the render()
function:
function Bike(props) {
return <h2>I am a {[Link]} Bike</h2>;
}
const root = [Link]([Link]('root'));
[Link](<Bike color="red"/>);
Props are also how you pass data from one component to another, as parameters.
Example
Send the "brand" property from the Garage component to the Car component:
function Show(props){
return <h1> My name is {[Link]} My age is {[Link]} </h1>;
}
const details={name: "rahul", age: "22"};
const root = [Link]([Link]('root'));
[Link](
<>
<Show person={ details }/>
</>
);
Props in the Constructor
If your component has a constructor function, the props should always be passed to
the constructor and also to the [Link] via the super() method.
Example
class Car extends [Link] {
constructor(props) {
super(props);}
render() {
return <h2>I am a {[Link]}!</h2>; }}
const root = [Link]([Link]('root'));
[Link](<Car model="Mustang"/>);
State
React Class Component State
React Class components have a built-in state object.
The state object is where you store property values that belongs to the component.
When the state object changes, the component re-renders.
import React from 'react';
class Car extends [Link] {
constructor() {
super()
[Link] = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My {[Link]}</h1>
<p>
It is a {[Link]}
{[Link]}
from {[Link]}.
</p>
</div>
);
}
}
export default Car;
Events

Handling events in React is similar to handling events in regular DOM elements, but
with some syntactic differences. Events are written in camelCase and you pass a
function as the event handler rather than a string.
Example of Handling Events in React
Let's break down how to handle events using a functional component with hooks.
import React from 'react';
import ReactDOM from 'react-dom/client';
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
const root = [Link]([Link]('root'));
[Link](<Football />);
Life cycle methods
In React, the life cycle of a component can be divided into four main phases:
• Initialization: Setting up the initial state and default props.
Constructor (constructor())
• Mounting: Adding the component to the DOM.
componentWillMount() (deprecated)
componentDidMount()
• Updating: Re-rendering the component when its state or props change.
componentWillReceiveProps() (deprecated)
shouldComponentUpdate()
componentWillUpdate() (deprecated)
componentDidUpdate()
• Unmounting: Removing the component from the DOM.
componentWillUnmount()
Conditional Rendering
Conditional rendering in React allows you to render different components or
elements based on certain conditions. Here are several common ways to achieve
conditional rendering in React:
1. Using if Statements
You can use an if statement to decide which component or element to render.
function MyComponent(props) {
const isLoggedIn = [Link];
if (isLoggedIn) {
return <UserDashboard />;
}
return <Login />;
}
[Link] if-else Statements
You can also use if-else statements for more complex conditions.
function MyComponent(props) {
const isLoggedIn = [Link];
if (isLoggedIn) {
return <UserDashboard />;
} else {
return <Login />;
}
}
3. Using Ternary Operator
The ternary operator is a concise way to handle simple conditional rendering.
function MyComponent(props) {
const isLoggedIn = [Link];
return (
<div>
{isLoggedIn ? <UserDashboard /> : <Login />}
</div>
);
}
4. Using Logical && Operator
For conditions where you only need to render something if a condition is true, you
can use the logical && operator.
function MyComponent(props) {
const isLoggedIn = [Link];
return (
<div>
{isLoggedIn && <UserDashboard />}
</div>
);
}
5. Using Switch Case
For more complex conditional rendering scenarios, you can use a switch statement.
function MyComponent(props) {
const userRole = [Link];
let component;
switch (userRole) {
case 'admin':
component = <AdminDashboard />; break;
case 'user':
component = <UserDashboard />;
break;
default:
component = <Login />; }
return <div>{component}</div>;
}
Introduction to state
management
State management in React involves managing the state of components and
ensuring that the data flows correctly throughout the application. Here’s a detailed
look at various state management techniques in React:
Local State
Local state is managed within a single component using the useState hook in
functional components or [Link] in class components.
Using useState in Functional Components
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Using [Link] in Class Components
import React, { Component } from 'react'; render() {
return (
<div>
class Counter extends Component { <p>You clicked {[Link]} times</p>
constructor(props) { <button onClick={[Link]}>
Click me
super(props); </button>
[Link] = { count: 0 }; </div>
} );
}
incrementCount = () => { }
[Link]({ count: [Link] + 1 });
}; export default Counter;
Context API
The Context API allows you to share state across the return (
entire component tree without passing props down <[Link] value={{ state, setState }}>
manually at every level. It is suitable for small to {children}
medium-sized applications. </[Link]>
Creating a Context );
}
import React, { createContext, useState } from 'react';

// Create a context
const MyContext = createContext();

function MyProvider({ children }) {


const [state, setState] = useState("some value");
Redux
Redux
Redux is a predictable state container for JavaScript apps, especially useful for large applications with
complex state interactions. It provides a single source of truth (the store) and uses actions and
reducers to manage state changes.
Setting Up Redux
Install Redux and React-Redux
npm install redux react-redux
// [Link]
export const increment = () => ({
type: 'INCREMENT'
});
export const decrement = () => ({
type: 'DECREMENT'
});
Create Reducer
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch ([Link]) {
case 'INCREMENT':
return { count: [Link] + 1 };
case 'DECREMENT':
return { count: [Link] - 1 };
default:
return state;
}}
export default counterReducer;
Create Store
// [Link]
import { createStore } from 'redux';
import counterReducer from './reducer';

const store = createStore(counterReducer);

export default store;


Provide the Store to Your App
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import Counter from './Counter';
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);}
export default App;
// [Link]
return (
import React from 'react';
<div>
import { useSelector, useDispatch } from 'react-redux'; <p>{count}</p>
import { increment, decrement } from './actions'; <button onClick={() =>
dispatch(increment())}>Increment</button>
<button onClick={() =>
function Counter() { dispatch(decrement())}>Decrement</button>
const count = useSelector(state => [Link]); </div>
);
const dispatch = useDispatch();
}

export default Counter;


React Router
• React Router is a library for routing in React applications. It allows you to create single-page
applications with navigation that feels like a multi-page application. React Router provides
components for managing the routing and rendering of different components based on the URL.
• Key Components of React Router
• BrowserRouter: A router implementation that uses the HTML5 history API (pushState,
replaceState, and the popstate event) to keep your UI in sync with the URL.
• Routes and Route: Define the component that should render when the user navigates to a specific
URL.
• Link: A component to create navigation links.
• NavLink: A special version of the Link component that can add styling attributes to the rendered
element when it matches the current URL.
• useNavigate: A hook to programmatically navigate.
• useParams: A hook to access the parameters of the current route.
• Outlet: A component that renders the matched child route.
React Router
import { BrowserRouter, Routes, Route,NavLink } from "react-router-dom";
import Home from "./Home";
<Routes>
import Register from "./Register";
import Login from "./Login"; <Route path=“Home" element={<Home />} />
import ReactDOM from "react-dom/client"; <Route path=“Register" element={<Register />} />
<Route path=“Login" element={<Login />} />

function Doing() { </Routes>


return (
</>
<> );
<NavLink to="/home">Home</NavLink> &nbsp;&nbsp; }
<NavLink to="/register">Register</NavLink> &nbsp;&nbsp;
const root =
<NavLink to="/login">Login</NavLink> &nbsp;&nbsp; [Link]([Link]('root'));
[Link](<BrowserRouter><Doing /></BrowserRouter>);
Fetch API
Using the Fetch API in React allows you to make network requests to fetch or send
data from/to a server. Here’s a comprehensive guide on how to use the Fetch API in a
React application.
Fetch API :
The Fetch API is a modern interface that allows you to make HTTP requests to servers
from web browsers. It is promise-based and provides a more powerful and flexible
feature set than the older XMLHttpRequest.
fetch('[Link]
.then(response => [Link]())
.then(data => [Link](data))
.catch(error => [Link]('Error fetching data:', error));
Fetch API in React
When using Fetch API in React, it’s common to make requests inside lifecycle
methods or using hooks like useEffect.
Using Fetch with Class Components
In class components, you typically make fetch requests in the componentDidMount
lifecycle method.
import React, { Component } from 'react';
class App extends Component {
constructor(props) { render() {
const { data, loading, error } = [Link];
super(props); if (loading) {
[Link] = { return <div>Loading...</div>;
data: null, }
if (error) {
loading: true, return <div>Error: {[Link]}</div>;
error: null }
return (
}; }
<div>
componentDidMount() { <pre>{[Link](data, null, 2)}</pre>
fetch('[Link] </div>
);
.then(response => [Link]()) }
.then(data => [Link]({ data, loading: false })) }
.catch(error => [Link]({ error, loading: false }));
export default App;
}
Using Fetch with Functional Components and Hooks
In functional components, the useEffect hook is used to perform side effects like
fetching data. The useState hook is used to manage the state.
import React, { useState, useEffect } from 'react';

function App() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
if (loading) {
fetch('[Link]
return <div>Loading...</div>;
.then(response => [Link]()) }
.then(data => { if (error) {
return <div>Error: {[Link]}</div>;
setData(data);
}
setLoading(false); return (
}) <div>
<pre>{[Link](data, null, 2)}</pre>
.catch(error => { </div>
setError(error); );
setLoading(false); }

}); export default App;


}, []); // Empty dependency array means this effect runs once on mount.
To use the Fetch API in React, you generally follow these steps:
Set up a new React component or use an existing one.
Use the useEffect hook to fetch data when the component mounts.
Manage the fetched data using the useState hook.
Here’s a step-by-step example:
Step 1: Set Up Your Component
Create a new component or use an existing one. Here, we’ll create a simple
component called DataFetcher.
Step 2: Use useEffect to Fetch Data
The useEffect hook allows you to perform side effects in your components. We'll use
it to fetch data when the component mounts.
Step 3: Manage State with useState
The useState hook lets you add state to your functional components. We'll use it to
store the fetched data.
import React, { useState, useEffect } from 'react';

const DataFetcher = () => {


const [data, setData] = useState(null); // State to store the fetched data
const [loading, setLoading] = useState(true); // State to manage the loading state
const [error, setError] = useState(null); // State to manage errors
useEffect(() => {
// Define the fetch function
const fetchData = async () => {
try {
const response = await fetch('[Link]
if (![Link]) {
throw new Error('Network response was not ok');
}
const result = await [Link]();
setData(result); // Update state with the fetched data
} catch (error) {
setError(error); // Update state with the error
} finally {
setLoading(false); // Set loading to false once the fetch is complete
} };
fetchData();
}, []); // Empty dependency array means this useEffect runs once when the component mounts
if (loading) {
return <div>Loading...</div>; // Show a loading message while data is being fetched
}
if (error) {
return <div>Error: {[Link]}</div>; // Show an error message if there was an error
}
return (
<div>
<h1>Fetched Data:</h1>
<pre>{[Link](data, null, 2)}</pre> {/* Display the fetched data */}
</div>
);};
export default DataFetcher;
State Management:
data: To store the fetched data.
loading: To manage the loading state.
error: To manage any errors that occur during the fetch.
Effect Hook:
The useEffect hook runs the fetch operation when the component mounts.
The fetchData function uses fetch to retrieve data from the API.
If the fetch is successful, it updates the data state with the fetched data.
If there's an error, it catches it and updates the error state.
The loading state is set to false after the fetch is complete, regardless of success or failure.
Conditional Rendering:
The component renders a loading message while data is being fetched.
If an error occurs, it displays the error message.
Once data is fetched successfully, it displays the data.
Axios
Using Axios in a React application is a common approach to handle HTTP requests. Axios is a promise-based HTTP
client that makes it easier to make requests and handle responses compared to the native fetch API. Here’s how
you can use Axios in a React component:
import React from 'react’; import axios from 'axios’; import {useState} from 'react';
function Student(){
const [data,setData]=useState([])
const getData=()=>{
[Link]('[Link]
.then(res=>{
[Link]([Link])
setData([Link])
}).catch(err=>{
[Link](err);
},[])
}
Axios
return (
<>
<br></br><br></br>
<button onClick={getData}>Get Student Data</button>
<br></br><br></br>
<table border="2" cellpadding="20">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>marks</td>
<td>Section</td>
<td>Branch</td>
</tr>
</thead>
<tbody>
{ [Link]((user,index)=>{
return <tr key={index}>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
</tr> })
}
</tbody>
</table>
</>
);}
export default Student;
import React from 'react';
import ReactDOM from 'react-dom/client';
import Student from './[Link]'

const root = [Link]([Link]('root'));


[Link](
<>
<Student/>
</>
);
@CrossOrigin(origins = "[Link] this in the spring boot rest api data
@RestController
public class StudentController {
@Autowired
StudentService ss;
@RequestMapping(value="/getData",method=[Link])
public List<Student> getStudent(){
return [Link]();
}
@RequestMapping(value="/addData",method=[Link])
public void addStudent(@RequestBody Student student){
[Link](student);
}
@RequestMapping(value="/delete/{id}",method=[Link])
public void deleteStudent( @PathVariable int id){
[Link](id);
}

@RequestMapping(value="/update/{marks}/
{id}",method=[Link])
public void updateStudent( @PathVariable int marks,@PathVariable int id){
[Link](marks, id);
}

}
Any Queries?

You might also like