KEMBAR78
React | PDF | Java Script | Document Object Model
0% found this document useful (0 votes)
7 views15 pages

React

Uploaded by

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

React

Uploaded by

spotifysaju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 15

What is React?

React is a JavaScript library developed by Facebook for building user


interfaces (UI), especially for single-page applications (SPAs) where
content updates dynamically without reloading the entire page.

Why Was React Invented? (History)


Problems Before React:

• DOM Manipulation was costly: Changing the UI directly with JavaScript


or jQuery caused performance issues.

• Spaghetti Code: Code became hard to manage as projects grew.

• Re-rendering Issues: Developers had to manage when and what part of


the DOM should update.

Origin:

• Developed by Jordan Walke, a Facebook engineer, in 2011.

• First used in Facebook’s newsfeed and then Instagram.

• Open-sourced in 2013.

What Makes React Different?


Other Tech (e.g.,
Feature React
jQuery)
UI broken into reusable Typically mixed HTML
Component-Based
components & JS everywhere
Real DOM manipulation
Virtual DOM Efficient rendering
(slow)
Predictable data flow Bi-directional (can get
Unidirectional Data
(top to bottom) messy)
Describe what to Imperative: Describe
Declarative
render how to update UI
HTML + JS combined
JSX Support Not available
(easy syntax)
Steps to Create a React App Using Vite (With
Explanation)

Navigate to Your Folder:cd /path/to/your/folder

◦ What it does: The cd command (change directory) moves you into the
folder where you want to set up your project.
◦ Why it’s needed: React projects need to be organized in a specific folder.
This keeps your app files and structure separate from other projects.

2. Create a Vite Project:npm create vite@latest my-vite-app


3.
◦ What it does: This command uses npm (Node Package Manager) to
download and run the Vite project setup tool. It initializes a new Vite
project in a folder named my-vite-app.
vite@latest: Ensures the latest version of Vite is used.
my-vite-app: This is the name of the folder/project. Replace it with your
desired app name.
◦ Why it’s needed: Vite provides the basic boilerplate (folder structure,
dependencies, and configuration) for your React app. Without this, you’d
have to manually configure everything.

4. Choose Framework and Variant:


◦ After running the above command, Vite asks you:
Which framework? Choose React (or any other framework like Vue or
Svelte if you're working with them).
Which variant? Choose JavaScript or TypeScript depending on your
preference.
◦ Why it’s needed: Vite supports multiple frameworks. Choosing React
ensures the boilerplate includes React-specific configurations. The variant
determines whether your project uses plain JavaScript or TypeScript.

4. Navigate into the App Directorycd my-vite-app


◦ What it does: Changes your working directory to the folder ( my-vite-
app) created by Vite.
◦ Why it’s needed: All subsequent commands will be executed in this
folder because it contains the files for your React project.

5. Install Dependencies:npm install

◦ What it does: Installs all the packages (dependencies) listed in the


package.json file.
◦ Why it’s needed: React and Vite require third-party libraries and tools to
function. npm install downloads and sets up these dependencies in the
node_modules folder.

6. Start the Development Server:npm run dev

◦ What it does: Runs the Vite development server, which:


Hosts your app locally at http://localhost:5173.
Automatically refreshes the browser whenever you make changes to your
code (hot reload).
◦ Why it’s needed: The development server allows you to preview your
app in the browser and see changes in real-time. Without it, you'd have to
manually refresh or reload your app after every change.

7. Open in VS Code:code .

◦ What it does: Opens the current folder in Visual Studio Code.


◦ Why it’s needed: VS Code provides an integrated environment for
editing, debugging, and managing your React app.

Why Can't React Be Used Like HTML or CSS?

React is not like HTML or CSS, where you can just write a file and open it
in a browser. Here's why:

1. React Uses JavaScript Logic:

◦ React relies on JavaScript to dynamically generate HTML using


components.
◦ Browsers do not understand React code (JSX) directly. It needs to be
transpiled into plain JavaScript using tools like Babel.
2. React Depends on a Build Process:

◦ React apps require a build system to convert modern JavaScript (ES6+


and JSX) into browser-compatible JavaScript.
◦ Tools like Vite or Webpack handle this process.
3. Why Extensions like .react Won’t Work:

◦ Browsers only recognize .html, .css, and .js files (and some additional
standard file types).
◦ React code (JSX) is a syntax extension of JavaScript, not a new file type. It
needs to be bundled and converted before it can be used.

Real-World Analogy for React Setup

Imagine you’re building a house:

• HTML and CSS: Prebuilt furniture (simple and static). You arrange them,
and they’re ready to use.
• React: Custom furniture that requires cutting, assembling, and finishing
(dynamic and reusable). Tools like Vite and Babel are your saws and drills,
preparing React for the browser.

Steps to Create a React App Using CRA

1. Install Node.js

• What to do:
◦ Download and install Node.js from the official Node.js website.
◦ Install the LTS (Long Term Support) version.
• Why it’s needed:
◦ Node.js provides the runtime for running JavaScript outside the browser.
◦ It also includes npm (Node Package Manager), which is used to manage
dependencies and create projects like React.

2. Open Terminal or Command Prompt

• Navigate to the folder where you want to create your React app
using:bashcd /path/to/your/folder

• Why it’s needed:


◦ React apps are created in specific directories to keep files organized.

3. Run the CRA Command

• Use the following command:npx create-react-app my-appReplace


my-app with your desired project name.
• Explanation:
◦ npx: Executes a package from npm without globally installing it.
◦ create-react-app: A command-line tool that sets up a new React
project with all the necessary configurations.
◦ my-app: This is the folder name for your React app.
• Why it’s needed:
◦ CRA automates the setup process, including adding configurations,
dependencies, and starter files.

4. Navigate to the Project Directory

• Move into the newly created app folder:cd my-app


Why it’s needed:
◦ All subsequent commands will run inside this project directory.

5. Start the Development Server

• Start your React app:npm start


• What it does:
◦ Launches a local development server and opens your app in the browser
at http://localhost:3000.
◦ Automatically reloads the browser whenever you save changes to your
code (hot reloading).
• Why it’s needed:
◦ Allows you to preview your app in real-time as you develop.

File Structure After Using CRA

After running the commands, CRA sets up a basic React app with the
following structure:

my-app/
├── node_modules/ # Installed dependencies
├── public/ # Static files (like index.html)
├── src/ # Your React components and app
code
│ ├── App.css # CSS for the App component
│ ├── App.js # Main App component
│ ├── index.css # Global CSS
│ └── index.js # Entry point of the app
├── .gitignore # Files to ignore in Git
├── package.json # Project metadata and
dependencies
├── README.md # Project documentation
└── yarn.lock or package-lock.json # Lock file for
dependencies

Why Use CRA?

• Preconfigured Setup: Handles all the configurations for tools like Babel,
Webpack, and ESLint.
• Boilerplate Code: Comes with a working React app to help you get
started.
• Cross-Browser Compatibility: Ensures your app works across different
browsers.

Comparison of CRA and Vite

Feature CRA Vite


Slower (more Faster (optimized
Setup Time
dependencies) bundling)
Slower during Extremely fast hot-
Performance
development reloading
Build Speed Decent Much faster
Pre-configured; harder Easier to customize
Flexibility
to customize and configure
What is Babel?

Babel is a JavaScript compiler that transforms modern JavaScript (ES6+


or JSX) into a version of JavaScript that older browsers or environments
can understand. This is crucial because not all JavaScript features (e.g.,
arrow functions, async/await, classes) are supported in every
browser.

Example Workflow

Using Babel:

1. You’d configure Babel with a .babelrc file or babel.config.js.


2. You’d integrate Babel into a bundler like Webpack to handle the build
process.
3. Babel compiles JSX and ES6+ to older JavaScript.
Using Vite:

1. No additional configuration is required for JSX or ES6+ support.


2. Vite automatically handles modern JavaScript and JSX.
3. Vite is faster because it doesn’t use bundling during development.

How Babel Relates to CRA and Vite

1. Babel in CRA:

◦ CRA includes Babel internally to transpile JSX and modern JavaScript to


browser-compatible code.
◦ You don’t need to configure Babel manually when using CRA.
2. Babel in Vite:

◦ Vite does not rely on Babel by default because it uses esbuild, which is
much faster than Babel for most transformations.
◦ However, if you need custom Babel transformations, you can integrate
Babel into a Vite project.

Which One to Choose?

• Use Babel:

◦ When you are working on a custom project setup and only need to
transpile JavaScript/JSX.
◦ Example: You want to build a small JavaScript library.
• Use CRA:

◦ When you’re new to React and need a simple setup to get started quickly.
◦ Best for beginners, though its performance may lag for larger projects.
• Use Vite:

◦ When you need a fast and modern development workflow.


◦ Best for performance and flexibility in modern projects.

What is JSX?

• Definition: JSX stands for JavaScript XML. It allows you to write HTML-
like syntax directly in JavaScript. It is then transformed into regular
JavaScript by tools like Babel before it is rendered in the browser.
• Why JSX?: It makes it easier to create React components and see the
structure of the UI.
Basic Syntax of JSX

• JSX code looks like this:

const element = <h1>Hello, World!</h1>;


• This is equivalent to:
javascript

const element = React.createElement("h1", null, "Hello,


World!");
• Embedding JavaScript in JSX: You can embed JavaScript expressions
inside {} in JSX.
jsx

import React from 'react';

const App = () => {


const name = "John";
return <h1>Hello, {name}!</h1>;
};

export default App;

What are Components in React?

A component in React is the building block of a user interface (UI).


Components allow you to split the UI into independent, reusable
pieces and manage them separately. Each component is like a JavaScript
function or class that takes inputs (called props) and returns React
elements describing what should appear on the screen.

Think of components as reusable, self-contained pieces of code that


manage their own state, logic, and UI rendering.
Types of Components

1. Functional Components:

◦ Written as JavaScript functions.


◦ Simpler and focus on rendering UI.
◦ Can use React Hooks (like useState and useEffect) for managing state
and lifecycle.
Class Components:

Written as ES6 classes.


Used before the introduction of Hooks.
Include more boilerplate code compared to functional components.

Example of Functional Component:

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

1. A Component Returns JSX: A component is just a function that returns


JSX, which is the structure of your UI:

2. A Component is Reusable: Once a component is created, it can be


reused anywhere in the app:function Welcome() {

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

function App() {
return (
<div>
<Welcome /> {/* Using the Welcome component */}
<Welcome /> {/* Reusing the same component */}
</div>
);
}

How to Render Components

React components need to be rendered into the DOM. This happens in the
main.jsx file, where you use ReactDOM.createRoot().

Steps:
1. Create a root component (usually App.jsx).
2. Import this component into main.jsx.
3. Render it using ReactDOM.createRoot().
Example:

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

ReactDOM.createRoot(document.getElementById("root")).rend
er(
<React.StrictMode>
<App />
</React.StrictMode>
);
App Component:

// App.jsx
import React from "react";
import Welcome from "./Welcome"; // Importing the Welcome
component

function App() {
return (
<div>
<Welcome /> {/* Rendering the Welcome component */}
</div>
);
}

export default App;


Child Component:

// Welcome.jsx
import React from "react";

function Welcome() {
return <h1>Welcome to React!</h1>;
}

export default Welcome;

Sample program for components

my-app/
├── node_modules/
├── public/
├── src/
│ ├── App.jsx // Root Component
│ ├── main.jsx // Entry Point
│ ├── Welcome.jsx // Child Component
│ └── index.css
├── package.json
├── vite.config.js
└── README.md

File: main.jsx

import React from "react";


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

ReactDOM.createRoot(document.getElementById("root")).rend
er(
<React.StrictMode>
<App />
</React.StrictMode>
);

Explanation:

1. import React from "react";

◦ This imports the React library, which is required to use JSX and build
components.
2. import ReactDOM from "react-dom/client";

◦ This imports ReactDOM, which is responsible for rendering the React


components into the DOM (browser's HTML).
3. import App from "./App";

◦ This imports the App component from the App.jsx file.


◦ App.jsx is the root component of your application where other
components are combined.
4. ReactDOM.createRoot(document.getElementById("root"))

◦ This creates a React "root" where the entire React application will be
rendered.
◦ document.getElementById("root") targets the <div
id="root"></div> in index.html.
5. .render(<React.StrictMode><App /></React.StrictMode>)

◦ This renders the App component inside the <div id="root"></div>.


◦ <React.StrictMode> is a wrapper used to highlight potential
issues in your code during development (not used in
production).

File: App.jsx

import React from "react";


import Welcome from "./Welcome"; // Importing the Welcome
component

function App() {
return (
<div>
<Welcome /> {/* Rendering the Welcome component */}
</div>
);
}

export default App;

Explanation:

1. import React from "react";

◦ This imports React so that we can use JSX in this file.


2. import Welcome from "./Welcome";

◦ This imports the Welcome component, which is defined in the


Welcome.jsx file.
3. function App()

◦ This is a functional component named App. It serves as the root


component for the application.
4. return (...)

◦ This is where the JSX is defined.


◦ The App component renders the Welcome component inside a <div>.
5. export default App;
◦ This exports the App component so it can be imported and used in other
files.

File: Welcome.jsx

import React from "react";

function Welcome() {
return <h1>Welcome to React!</h1>;
}

export default Welcome;

Explanation:

1. import React from "react";

◦ This imports React, which is necessary for using JSX in this file.
2. function Welcome()

◦ This is a functional component named Welcome.


3. return <h1>Welcome to React!</h1>;

◦ This returns JSX, which renders an <h1> element with the text "Welcome
to React!".
4. export default Welcome;

◦ This exports the Welcome component so it can be imported and used in


other files.

How Everything Works Together

1. Rendering in main.jsx:

◦ The App component is rendered into the #root div in index.html.


2. The App Component:

◦ The App component acts as the parent and includes the Welcome
component.
3. The Welcome Component:

◦ The Welcome component is a child component that renders a simple <h1>


element.

Shortcut to Create Components Using ES7+ Snippets


If you want to save time while creating components, use the ES7+
React/Redux/React-Native snippets extension in VS Code.

Steps:

1. Install the extension ES7+ React/Redux/React-Native snippets from


the VS Code Extensions marketplace.
2. Use the following shortcuts:
◦ To create a functional component: Type rafce and press Enter. This
will auto-generate the boilerplate code for a React functional
component:jsx
Testing Your Application

1. Start the development server:npm run dev


2. Open http://localhost:5173 in your browser.
3. You should see "Welcome to React!" displayed on the screen.

Styling React components can be done in various ways depending on the


project requirements and preferences. Below are the most common
methods to style React components with examples.

1. Inline Styles

Inline styles are written as a JavaScript object where the properties use
camelCase instead of kebab-case.

Example:

import React from "react";

function App() {
const style = {
color: "blue",
backgroundColor: "lightgray",
padding: "10px",
borderRadius: "5px",
};

return <h1 style={style}>Hello, Inline Styling!</h1>;


}

export default App;


Pros:

• Simple for small and dynamic styles.


• Easy to apply conditional styling.
Cons:

• Cannot use pseudo-classes like :hover.


• Not ideal for complex styles.

2. CSS Stylesheets

You can create a separate .css file and link it to your component.

Example:

1. Create a styles.css file:h1 {

color: green;
background-color: lightyellow;
padding: 10px;
border-radius: 5px;}

2. Import the CSS file in your React component: import React from
"react";

import "./styles.css";

function App() {
return <h1>Hello, CSS Styling!</h1>;
}

export default App;

Pros:

• Easy to maintain and reuse styles.


• Supports pseudo-classes and media queries.
Cons:

• Styles can leak globally, affecting other components.

4. Styled Components (CSS-in-JS)

Styled Components is a popular library for writing CSS in JavaScript using


tagged template literals.

Example:

npm install styled-components


import React from "react";
import styled from "styled-components";

const Title = styled.h1`


color: purple;
background-color: lightgreen;
padding: 10px;
border-radius: 5px;
`;

function App() {
return <Title>Hello, Styled Components!</Title>;
}

export default App;


Pros:

• Component-specific styling.
• Dynamic styling using props.
• Supports pseudo-classes and media queries.
Cons:

• Adds an external dependency.

You might also like