0% found this document useful (0 votes)
8 views21 pages

10 ReactJS Function Components

The document provides an overview of ReactJS Function Components, explaining their structure, how they handle props, and the use of hooks for state management. It discusses the differences between functional and class components, the process of exporting and importing components, and how to handle input fields and events. Additionally, it covers the concept of destructuring props and the importance of using the useState hook for managing component state.
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)
8 views21 pages

10 ReactJS Function Components

The document provides an overview of ReactJS Function Components, explaining their structure, how they handle props, and the use of hooks for state management. It discusses the differences between functional and class components, the process of exporting and importing components, and how to handle input fields and events. Additionally, it covers the concept of destructuring props and the importance of using the useState hook for managing component state.
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
You are on page 1/ 21

ReactJS Function

Components
Function Components
• React Function Components, also known as React Functional
Components.
• They are simple, lightweight, and powerful tools for rendering UI and
handling logic.
• Functional components can accept props as input and return JSX that
describes what the component should render.
• When a functional component receives input and is rendered, React
uses props and updates the virtual DOM to ensure the UI reflects the
current state.
Function Components
• Props: Functional components receive input data through props,
which are objects containing key-value pairs.
• Processing Props: After receiving props, the component processes
them and returns a JSX element that defines the component's
structure and content.
• Virtual DOM: When the component is rendered, React creates a
virtual DOM tree that represents the current state of the application.
• Re-rendering: If the component's props or state change, React
updates the virtual DOM tree accordingly and triggers the component
to re-render.
Function Components
import React from 'react';

function App() {
const greeting = 'Hello Function Component!';
return <h1>{greeting}</h1>;
}
• Each time React needs to render <App />, it calls the function again.
• That means everything inside App() is re-executed on every render.
Variables function CounterFunction() {
let count = 0; // local variable

• var, let, const variables function handleClick() {


inside a component are count = count + 1; // incrementing
recreated every render. console.log("Clicked:", count);
};
• They don’t persist — React return (
wipes them out and reruns <div>
the function. <p>Count: {count}</p>
• To persist values across <button
renders, you use state onClick={handleClick}>Increment</button>
(useState) </div>
);
}
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
); }
}
ReactJS Hooks
• Introduced in React 16.8, are among the most impactful updates to
the library
• They let developers use state, side effects, and other React features
without writing class components.
• Hooks are special functions that let you “hook into” React features
(like state and lifecycle methods) in functional components.
• State hooks, specifically useState and useReducer, allow functional
components to manage state.
• They provide an easier and cleaner approach to managing
component-level states in comparison to class components.
ReactJS Hooks import { useState } from "react";

export default function App() {


const [count, setCount] = useState(0); // state variable
• useState: The useState hook is used
to declare state variables in const handleClick = () => {
setCount(count + 1); // update state
functional components. console.log("Clicked:", count + 1);
• const [state, setState] = };
useState(initialState);
return (
• state: The current value of the state. <div>
<p>Count: {count}</p>
• setState: A function used to update <button onClick={handleClick}>Increment</button>
the state. </div>
);
• initialState: The initial value of the }
state
Exporting a Component
• Default export
export default function Greeting() {
return <h1>Hello from Greeting!</h1>;
}
• Only one default export is allowed per file.

• Named Export
• You can export multiple things from the same file.

export function add(a, b) {


return a + b;
}

export function subtract(a, b) {


return a - b;
Importing a Component
• You can name them whatever • You must use the exact same name
you like when importing inside { }

import Greeting from "./Greeting"; import { add, subtract } from "./Utils";


function App() {
return ( console.log(add(5, 3)); // 8
<div> console.log(subtract(5, 3)); // 2
<Greeting />
</div>
);
}
Mix of Default + Named Exports
// File: MathOps.js
export default function multiply(a, b) { import multiply, { divide } from "./MathOps";
return a * b;
} console.log(multiply(3, 4)); // 12
console.log(divide(8, 2)); // 4
export function divide(a, b) {
return a / b;
}
Props to a ReactJS Functional
Component
• Props are used to pass data from a parent component to a child
component.
• Props are read-only and allow you to make a component dynamic by
passing different values into it.
function App() { import React from 'react';
return (
<div> function Greeting(props) {
<Greeting message="Hello, World!" return <h2>{props.message}</h2>;
</div> }
);
} export default Greeting;
Destructuring Props
• Instead of using props.name, you can destructure the props object directly in the
function’s argument

import React from 'react';

// Functional Component with destructuring


const Welcome = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};

// Parent Component
const App = () => {
return <Welcome name="Jiya" />;
};
Handling Input fields
return (
export default function App() { <div>
<h2>Single Input Example</h2>
// single state variable for username
const [username, setUsername] = useState(""); <input
type="text"
// update username when user types placeholder="Enter Username"
const handleChange = (e) => { value={username}
setUsername(e.target.value); onChange={handleChange}
}; />
<p>Username: {username}</p>
</div>
);
}
What is ‘e’ in handling function
• When you attach an event handler in React (e.g., onChange={handleChange}),
• React automatically passes an event object to your function.
• This object is usually named e (short for event).
• Inside an event, target is the element that triggered the event.
• If you type into <input>, then e.target is that <input> element.
• e.target // refers to the input DOM element
• e.target.value // gives you whatever the user typed into the input
Handling Input Fields
• <input type="text" onChange={(e) => console.log(e.target.value)} />
• You type Hello into the box:
• First keystroke: console shows H
• Next: He
• Then: Hel
• Then: Hell
• Finally: Hello
• Because each time you type, the event fires
• React passes e (event)
• e.target is the input and .value is the latest input text.
Handling Inputs
• const [username, setUsername] = useState("");
• Why do we use const for usename instead of let or var?
• useState always gives you exactly two things:
• the current state value (username)
• the updater function (setUsername)
• This pair will not change identity during the lifetime of the
component.
• You’ll always have the same setUsername function.
• username is replaced with a new value only when React re-
renders, not by reassignment.
Handling Inputs
• const [username, setUsername] = useState("");
• const mean cannot reassign the variable identifier.
• But if the const holds a reference to an object or function, the reference itself
is constant, but the internal data can change.
• const user = { name: "Alice", age: 25 };

• // Allowed: we can change internal properties


• user.age = 26;
• console.log(user); // { name: "Alice", age: 26 }

• // Not allowed: cannot reassign the whole object


• user = { name: "Bob" }; // Error
Handling Inputs• const [username, setUsername] = useState("Alice");
• username is like the value ("Alice" initially).
const greet = function(name) { • You don’t reassign it (username = "Bob"; ).
return "Hello " + name; • React gives you a new snapshot on re-render when
}; you call setUsername.
// greet = () => "Hi"; // Error • setUsername("Bob");
console.log(greet("Alice")); // "Hello • telling React: “please update the stored value of
Alice" username to 'Bob' ”.
• React puts "Bob" into its internal state storage
(separate from your function variables).
• On re-render:
• React doesn’t use "Alice" again — it retrieves the
latest stored value "Bob".
Handling Inputs
• First render : username = "Alice“
• User types / you call setUsername("Bob")
• React updates internal state and schedules re-render
• Component runs again: now username = "Bob"

You might also like