0% found this document useful (0 votes)
30 views

MERN Manual-Reactprograms

MERN Stack program of React JS for beginners

Uploaded by

Harsha Hegde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

MERN Manual-Reactprograms

MERN Stack program of React JS for beginners

Uploaded by

Harsha Hegde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

MERN Stack is a JavaScript Stack that is used for easier and faster deployment of full-

stack web applications. MERN Stack comprises of 4 technologies


namely: MongoDB, Express, React and Node.js. It is designed to make the development
process smoother and easier.
• MongoDB: Non-Relational Database
• Express: Node.js web server
• React: JavaScript Frontend Framework
• Node: JavaScript Web Server
Getting Started with MERN Stack:
There are two requirements to start a MERN stack project:
Step 1: Install node on your system depending on your Operating System:
• Installation of Node.js on Windows
• Installation of Node.js on Linux
Step 2: You need a code editor to work with so install a code editor, preferably will use VS
Code
Setting Up a MERN Stack Project
To setup MERN stack we need to create a folder structure for both frontend and backend.
Then we have to define database schema to store and retrieve data from the database.
Follow the below steps to create a basic structure
Step 1: After the code editor is installed, create a new project folder. Then go to the project
folder in command prompt/terminal and type below commands to create folder for frontend
and backend
mkdir frontend
mkdir backend
Step 2: Navigate to the frontend folder using the command
cd frontend
Step 3: Initialize a React Project using the command
npx create-react-app
Step 4: Now navigate to the backend folder using the command
cd..
cd backend
Step 5: Initialize the project backend using the command
npm init -y
Step 6: Install Express and other backend dependencies using the command
npm i mongodb express cors dotenv

React Lifecycle Phases


React Lifecycle is defined as the series of methods that are invoked in different stages of the
component’s existence. A React Component can go through four stages of its life as follows.
The React lifecycle is divided into three main phases:
1. Initialization phase: This is the stage where the component is constructed with the
given Props and default state. This is done in the constructor of a Component Class.
2. Mounting Phase: This phase begins when a component is created and inserted into
the DOM.
3. Updating Phase: This occurs when a component is re-rendered due to changes in
props or state.
4. Unmounting Phase: This is the final phase when a component is removed from the
DOM.
PROGRAM 1
Demonstrate React Component Life Cycle-Mounting phase—constructor method
import React from "react";
import ReactDOM from "react-dom/client";

class Test extends React.Component {


constructor(props) {
super(props);
this.state = {hello: "World!"};
}

render() {
return (
<div>
<h1>
Hello
{this.state.hello}
</h1>
</div>
);
}
}

const root = ReactDOM.createRoot


(
document.getElementById("root")
);
root.render(<Test />);

o/p:

PROGRAM 2
Demonstrate React Component Life Cycle-Mounting phase--static
getDerivedStateFromProps method
import React, { Component } from "react";
import ReactDOM from "react-dom/client";

class Counter extends Component {


state = {
count: this.props.initialCount,
};

static getDerivedStateFromProps(props, state) {


// Check if the initial count prop has changed
if (props.initialCount !== state.count) {
// Update the state with the new initial count
return {
count: props.initialCount,
};
}
return null;
}

handleIncrement = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button
onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}

class App extends Component {


state = {
initialCount: 0,
};

handleInitialCountChange = (e) => {


const newInitialCount = parseInt(e.target.value, 10);
this.setState({ initialCount: newInitialCount });
};

render() {
return (
<div className='App'>
<h1>Counter App</h1>
<label>
Initial Count:
<input
type="number"
value={this.state.initialCount}
onChange={this.handleInitialCountChange}
/>
</label>
<Counter initialCount={this.state.initialCount} />
</div>
);
}
}

const root = ReactDOM.createRoot(


document.getElementById("root")
);
root.render(<App/>);

PROGRAM 3
Demonstrate React Component Life Cycle-Mounting phase -render() method:
// Filename - index.js

import React from "react";


import ReactDOM from "react-dom/client";

class Test extends React.Component {


render() {
return (
<div>
<h1>
hello world
</h1>
</div>
);
}
}

const root = ReactDOM.createRoot(


document.getElementById("root")
);
root.render(<Test />);

PROGRAM 4
Demonstrate React Component Life Cycle-Mounting phase-componentDidMount()
Function
// Filename - index.js

import React from "react";


import ReactDOM from "react-dom/client";

class Test extends React.Component {


constructor(props) {
super(props);
this.state = { hello: "hello!" };
}
componentDidMount() {
this.setState({hello:"world!"})
}
render() {
return (
<div>
<h1>
heloo
{this.state.hello}
</h1>
</div>
);
}
}

const root = ReactDOM.createRoot(


document.getElementById("root")
);
root.render(<Test />);

PROGRAM 5
Demonstrate React Component Life Cycle-updation phase --setState() method

// Filename - index.js

import React from "react";


import ReactDOM from "react-dom/client";

class App extends React.Component {


constructor(props) {
super(props);
this.state = {
count: 0,
};
}

increment = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};

decrement = () => {
this.setState((prevState) => ({
count: prevState.count - 1,
}));
};

render() {
return (
<div>
<h1>
The current count is :{" "}
{this.state.count}
</h1>
<button onClick={this.increment}>
Increase
</button>
<button onClick={this.decrement}>
Decrease
</button>
</div>
);
}
}

const root = ReactDOM.createRoot(


document.getElementById("root")
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

PROGRAM 6
Demonstrate React Component Life Cycle-Unmounting phase --
componentWillUnmount() method

import React from "react";


import ReactDOM from "react-dom/client";
class ComponentOne extends React.Component {
// Defining the componentWillUnmount method
componentWillUnmount() {
alert("The component is going to be unmounted");
}

render() {
return <h1>Hello sahyadri</h1>;
}
}

class App extends React.Component {


state = { display: true };
delete = () => {
this.setState({ display: false });
};

render() {
let comp;
if (this.state.display) {
comp = <ComponentOne />;
}
return (
<div>
{comp}
<button onClick={this.delete}>
Delete the component
</button>
</div>
);
}
}

const root = ReactDOM.createRoot(


document.getElementById("root")
);
root.render(<App />);

PROGRAM 7
Develop a React Component for basic front-end application-registration form
// Filename - src/index.js:

import React from "react";


import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(


document.getElementById("root")
);
root.render(<App />);

// Filename - src/App.js:

import './App.css';
import Form from "./Form"

function App() {
return (
<div className="App">
<Form />
</div>

);
}

export default App;


// Filename – src/Form.js

import { useState } from "react";

export default function Form() {


// States for registration
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");

// States for checking the errors


const [submitted, setSubmitted] = useState(false);
const [error, setError] = useState(false);

// Handling the name change


const handleName = (e) => {
setName(e.target.value);
setSubmitted(false);
};

// Handling the email change


const handleEmail = (e) => {
setEmail(e.target.value);
setSubmitted(false);
};

// Handling the password change


const handlePassword = (e) => {
setPassword(e.target.value);
setSubmitted(false);
};

// Handling the form submission


const handleSubmit = (e) => {
e.preventDefault();
if (name === "" || email === "" || password === "") {
setError(true);
} else {
setSubmitted(true);
setError(false);
}
};

// Showing success message


const successMessage = () => {
return (
<div
className="success"
style={{
display: submitted ? "" : "none",
}}
>
<h1>User {name} successfully registered!!</h1>
</div>
);
};

// Showing error message if error is true


const errorMessage = () => {
return (
<div
className="error"
style={{
display: error ? "" : "none",
}}
>
<h1>Please enter all the fields</h1>
</div>
);
};

return (
<div className="form">
<div>
<h1>User Registration</h1>
</div>

{/* Calling to the methods */}


<div className="messages">
{errorMessage()}
{successMessage()}
</div>

<form>
{/* Labels and inputs for form data */}
<label className="label">Name</label>
<input
onChange={handleName}
className="input"
value={name}
type="text"
/>
<br></br>
<label className="label">Email</label>
<input
onChange={handleEmail}
className="input"
value={email}
type="email"
/>
<br></br>
<label className="label">Password</label>
<input
onChange={handlePassword}
className="input"
value={password}
type="password"
/>
<br></br>
<button onClick={handleSubmit} className="btn" type="submit">
Submit
</button>
</form>
</div>
);
}

/* Filename: App.css */

.App {
text-align: center;
background-color: green;
}

.label {
display: block;
font-size: larger;
color: white;
padding: 5px;
}

.input {
font-size: larger;
padding: 5px;
margin: 2px;

.btn {
color: white;
background-color: red;
border-radius: 5px;
font-size: larger;
display: block;
padding: 5px;
margin: 10px auto;
}
.messages {
display: flex;
justify-content: center;
}

.error {
display: block;
background-color: red;
color: white;
width: fit-content;
height: 50px;
padding: 5px;
}

.success {
display: block;
background-color: lightblue;
color: black;
width: fit-content;
height: 50px;
padding: 5px;
}

You might also like