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

React task

In React, rendering is the process of displaying UI elements based on component state and props, utilizing a virtual DOM for efficiency. There are several types of rendering including initial rendering, re-rendering, server-side rendering (SSR), client-side rendering (CSR), static site generation (SSG), incremental static regeneration (ISR), and hydration. The document also provides examples of creating and rendering components, implementing routing with React Router, and handling forms for dynamic calculations.

Uploaded by

Rohan Malik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

React task

In React, rendering is the process of displaying UI elements based on component state and props, utilizing a virtual DOM for efficiency. There are several types of rendering including initial rendering, re-rendering, server-side rendering (SSR), client-side rendering (CSR), static site generation (SSG), incremental static regeneration (ISR), and hydration. The document also provides examples of creating and rendering components, implementing routing with React Router, and handling forms for dynamic calculations.

Uploaded by

Rohan Malik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

What is "Render" in React?

In React, rendering refers to the process of displaying UI elements on the


screen based on the current state and props of components. React uses a
virtual DOM to efficiently update the real DOM, ensuring optimal
performance.

Types of Rendering in React

Rendering can be categorized into the following types:

1. Initial Rendering

Definition: This is the first rendering of a React component, where the UI is


built for the first time.

When It Happens: When the app starts or a new component is mounted.

Example:

function App() {

return <h1>Welcome to React</h1>;

The above code initially renders the <h1> tag.

2. Re-rendering

Definition: Happens when a component updates due to changes in its state


or props.

When It Happens:

A state variable is updated.

New props are passed to a component.

Example:

import React, { useState } from 'react';

function Counter() {

const [count, setCount] = useState(0);


return (

<div>

<p>Count: {count}</p>

<button onClick={() => setCount(count + 1)}>Increment</button>

</div>

);

Clicking the button triggers a re-render as the state (count) updates.

3. Server-side Rendering (SSR)

Definition: The process of rendering components on the server and sending


the fully-formed HTML to the browser.

Purpose: Improves performance and SEO.

When It Happens: Typically implemented using frameworks like Next.js.

Example:

Code is rendered on the server using libraries like ReactDOMServer.

4. Client-side Rendering (CSR)

Definition: The traditional way of rendering in React, where the JavaScript


code is executed in the browser to render components.

When It Happens: By default in React apps created using create-react-app.

Example:

import ReactDOM from 'react-dom';

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

5. Static Site Generation (SSG)

Definition: Pre-rendering HTML pages at build time and serving static files.

Purpose: Combines the speed of static files with the dynamic nature of
React.
When It Happens: Popular in frameworks like Next.js.

6. Incremental Static Regeneration (ISR)

Definition: A hybrid approach where static pages are regenerated at


runtime after a specified period or based on conditions.

When It Happens: Used in modern frameworks like Next.js for dynamic


content that changes infrequently.

7. Hydration

Definition: A process where the React application takes over the static
HTML and binds it to React's state and interactivity.

When It Happens: During server-side rendering, when the app "hydrates"


the server-rendered HTML in the browser.

1. Creating and Rendering Multiple Components

import React from 'react';

import ReactDOM from 'react-dom/client';

function Header() {

return <h1>Welcome to My Website</h1>;

function Footer() {

return <footer>© 2024 My Website</footer>;

function App() {

return (

<div>

<Header />

<p>This is the main content of the website.</p>

<Footer />

</div>
);

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<App />);

2. Creating a Component Inside Another Component

import React from 'react';

import ReactDOM from 'react-dom/client';

function App() {

function InnerComponent() {

return <p>This is an inner component.</p>;

return (

<div>

<h1>Hello World!</h1>

<InnerComponent />

</div>

);

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<App />);

3. Splitting Components into Different Files


File 1: Header.js

import React from 'react';


function Header() {

return <h1>Welcome to My Website</h1>;

export default Header;

File 2: Footer.js

import React from 'react';

function Footer() {

return <footer>© 2024 My Website</footer>;

export default Footer;

File 3: App.js

import React from 'react';

import Header from './Header';

import Footer from './Footer';

function App() {

return (

<div>

<Header />

<p>This is the main content of the website.</p>

<Footer />

</div>

);

export default App;

File 4: 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 />);

Step 1: Create Components for Each Tab

Create individual components for each tab in the navigation bar.

File 1: Home.js

import React from 'react';

function Home() {

return <h1>Welcome to the Home Page</h1>;

export default Home;

File 2: About.js

import React from 'react';

function About() {

return <h1>About Us</h1>;

export default About;

File 3: Contact.js

import React from 'react';

function Contact() {

return <h1>Contact Us</h1>;

export default Contact;

File 4: Services.js
import React from 'react';

function Services() {

return <h1>Our Services</h1>;

export default Services;

Step 2: Create the Navigation Bar with Routing

File 5: App.js

import React from 'react';

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-


dom';

import Home from './Home';

import About from './About';

import Contact from './Contact';

import Services from './Services';

function App() {

return (

<Router>

<div>

{/* Navigation Bar */}

<nav>

<ul style={{ display: 'flex', listStyle: 'none', gap: '20px' }}>

<li><Link to="/">Home</Link></li>

<li><Link to="/about">About</Link></li>

<li><Link to="/services">Services</Link></li>
<li><Link to="/contact">Contact</Link></li>

</ul>

</nav>

{/* Routes to Render Components */}

<Routes>

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

<Route path="/services" element={<Services />} />

<Route path="/contact" element={<Contact />} />

</Routes>

</div>

</Router>

);

export default App;

Step 3: Render the Application

File 6: 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 />);

Steps to Solve:

1. Set up the project: Install React Router if not already installed.


npm install react-router-dom

2. Create the Components: Create individual components for Home, Portfolio,


Projects, Contact Me, JavaScript, and Result.

3. Setup React Router: Use BrowserRouter, Routes, and Route to navigate


between the components.

---

Code Implementation:

1. App.js (Main Application File)

import React from "react";

import { BrowserRouter as Router, Routes, Route, Link } from "react-router-


dom";

import Home from "./components/Home";

import Portfolio from "./components/Portfolio";

import Projects from "./components/Projects";

import ContactMe from "./components/ContactMe";

import JavaScript from "./components/JavaScript";


import Result from "./components/Result";

function App() {

return (

<Router>

<div>

{/* Navigation Bar */}

<nav>

<ul>

<li><Link to="/">Home</Link></li>

<li><Link to="/portfolio">Portfolio</Link></li>

<li><Link to="/projects">Projects</Link></li>

<li><Link to="/contact">Contact Me</Link></li>

<li><Link to="/javascript">JavaScript</Link></li>

<li><Link to="/result">Result</Link></li>

</ul>

</nav>

{/* Routes */}

<Routes>

<Route path="/" element={<Home />} />

<Route path="/portfolio" element={<Portfolio />} />

<Route path="/projects" element={<Projects />} />

<Route path="/contact" element={<ContactMe />} />

<Route path="/javascript" element={<JavaScript />} />

<Route path="/result" element={<Result />} />

</Routes>
</div>

</Router>

);

export default App;

---

2. Home.js

import React from "react";

const Home = () => {

return (

<div>

<h1>About Me</h1>

<p>Details about myself.</p>

<h2>Concepts Learned:</h2>

<ul>

<li>React Basics</li>

<li>State Management</li>

<li>React Router</li>

<li>Component Lifecycle</li>

</ul>

<h2>Mini Projects:</h2>
<ul>

<li>Todo App</li>

<li>Weather App</li>

</ul>

<h2>Course Expectations:</h2>

<p>To gain hands-on experience in React and build real-world


projects.</p>

</div>

);

};

export default Home;

---

3. Portfolio.js

import React from "react";

const Portfolio = () => {

return <h1>Portfolio Page</h1>;

};

export default Portfolio;


---

4. Projects.js

import React from "react";

const Projects = () => {

return (

<div>

<h1>Projects</h1>

<ul>

<li>Todo App</li>

<li>E-commerce Site</li>

<li>Portfolio Website</li>

</ul>

</div>

);

};

export default Projects;

---

5. ContactMe.js

import React from "react";


const ContactMe = () => {

return (

<div>

<h1>Contact Me</h1>

<p>Email: [email protected]</p>

<p>Phone: +1234567890</p>

</div>

);

};

export default ContactMe;

---

6. JavaScript.js

import React from "react";

const JavaScript = () => {

return <h1>JavaScript Concepts</h1>;

};

export default JavaScript;

7. Result.js
import React, { useState } from "react";

const Result = () => {

const [formData, setFormData] = useState({

name: "",

email: "",

subjects: ["", "", "", "", ""],

marks: ["", "", "", "", ""],

});

const [result, setResult] = useState(null);

const handleChange = (e) => {

const { name, value } = e.target;

setFormData((prev) => ({

...prev,

[name]: value,

}));

};

const handleSubjectChange = (index, value) => {

const subjects = [...formData.subjects];

subjects[index] = value;

setFormData({ ...formData, subjects });

};
const handleMarksChange = (index, value) => {

const marks = [...formData.marks];

marks[index] = value;

setFormData({ ...formData, marks });

};

const calculateResult = () => {

const totalMarks = formData.marks.reduce(

(acc, mark) => acc + parseInt(mark || 0),

);

const percentage = (totalMarks / (formData.marks.length * 100)) * 100;

setResult({

name: formData.name,

subjects: formData.subjects,

totalMarks,

percentage,

});

};

return (

<div>

<h1>Student Result</h1>

<form

onSubmit={(e) => {

e.preventDefault();
calculateResult();

}}

>

<label>

Name:

<input type="text" name="name" onChange={handleChange} />

</label>

<br />

<label>

Email:

<input type="email" name="email" onChange={handleChange} />

</label>

<br />

{formData.subjects.map((_, index) => (

<div key={index}>

<label>

Subject {index + 1}:

<input

type="text"

onChange={(e) => handleSubjectChange(index, e.target.value)}

/>

</label>

<label>

Marks:

<input

type="number"

onChange={(e) => handleMarksChange(index, e.target.value)}


/>

</label>

</div>

))}

<button type="submit">Calculate Result</button>

</form>

{result && (

<div>

<h2>Result</h2>

<p>Name: {result.name}</p>

<ul>

{result.subjects.map((subject, index) => (

<li key={index}>

{subject}: {formData.marks[index]} marks

</li>

))}

</ul>

<p>Total Marks: {result.totalMarks}</p>

<p>Percentage: {result.percentage.toFixed(2)}%</p>

</div>

)}

</div>

);

};

export default Result;

Explanation:
Routing: React Router is used to link components and navigate between
pages.

Form: The Result component dynamically calculates the total marks and
percentage based on user input.

You might also like