2026-08-19 12:10
Status:
Tags: IBM IBM Full Stack Software Developer Professional Certificate IBM - Developing Front-End Apps with React Front End React Websites Web Development Software Programming HTML JavaScript
IBM - DFAR - Understanding Function Components with Array and DOM Manipulation
==Introduction to Function Components
-
Working with Function Components: Props and Event Handling:
-
Props / Properties- these allow for data flow between on component and another. It works similar to an object.
-
It stores data by storing the attributes of a parent component and letting you pass them on to the child component
-
-
This data is Read only, meaning that you cannot change it inside of a child
-
In this example, the parent component is the app, the child is the employee data, and then the data that is getting passed in is the name John.
-
This sets the attribute data of name inside of the employee data component
-
-
As seen, you can pass in the props parameter inside of the component, and then you also then see the state inside of that props parameter also hold the name, generally it can be anything but props is the things that people should ue
-
-
You can also pass the data in order ways, like having a variable of the parent app and then passing that over basically
-
-
There is also the concept of default prop values where you can define default prop values inside of a child component and this basically lets you still have data inside of there even if the actual parent application does not provide any of that information
-
Principles behind Usefulness of Props
- Re-usability
- Unidirectional data flow
- Customization
- Composition
-
Re-usability- passing in different props lets you reuse the same component without the actual duplication of code, and you can customize the different behaviors of your components based on different values of data
-
Unidirectional Data Flow- it makes it easy to see how data flows and gets passed in the application, making the code readable and understandable
-
Customization- you can write code that is simple and yet robust, the props allow for flexibility with what you want to be done
-
Composition- keeps your code simple when building pretty complex Uis
-
-
-
In the above hand code, you are passing in the prop attribute of
increasewith the value of ten thousand dollars. -
Inside of the then props component, the use of a state hook basically allows you to see if an increase has or has not occurred, letting you take in data from an above hand source and then dynamically show case if an increase has happened
-
This way, a hook and react state component can interact with each other
-
The above hand is also how a hook component would work, basically allowing you to declare internal state within of the object, the
useState(false)function basically sets a default value for that state, and then you can generally change said state with the function that is defined in the same line
-
-
Component Composition:
- Composition- you can actually combine multiple components using composition
- With function components, you can combine multiple smaller components in order to create one larger, more complex UI
- Sort of like smaller building blocks that you can reuse to build a larger more complex structure
- Principles of Composition
- Abstraction
- Re-usability
- Hierarchy
- Props and Children
- Higher-order components (HOCs)
- Abstraction- this basically means that you can make smaller components out of a bigger thing, letting you abstract away the complex and hard to understand portions of an application, and work on them in smaller more manageable parts
- Re-usability you can then basically use these abstracted out components however much and wherever much is it that you would like
- Hierarchy- this lets you array components inside of a hierarchy, with parent and child components that can receive data, letting you have an even easier time with implementation of modular design and abstraction
- Props and Children- basically what has already been covered, there is a unidirectional flow of data between the two, and the data exchanged between the two cannot be changed by the ladder
- Higher-Order Components- these are basically functions that take in other components as input, and can also then return a component with a more enchanced functionality than what was inputed inside of them
- This lets you add features and state without modifying implementation
-
State Management in Function Components:
- State is basically the thing that you would use to manage the data that can change over time inside of a component
- State basically refers to the condition of that component at a specific time
- It holds information that can influence the behavior of the object, and also force it to re-render if that state gets updated
- State Management- generally, before hooks were a thing, you could not control the local state of a component, but with them, you can
- Hooks allow you to reuse code logic without changing component hierarchy & nesting
- They make it easier to share and compose functionality across components
useState- this basically allows you to add state management to function components, and manage it given some other hand function that you also define in the same line- It would generally have a single given starter value, and then would be changed based on the logic needed in your code
- The syntax of this uses array destructuring for the const variable, which basically allows you to extra values from an array, and directly assign them to given variables
- Using this feature lets you basically take what I can only assume to be the output of the
useStatefunction to assign an initial value to the first var and then the function connected to that same var within of the second var - I wonder how this would work with type script where there is no automatic type resolution
stateName- stores the current state value, can be accessed and updated as neededsetStateName- used to update the state value, whenever this is actually called, react re-renders that component- Then basically in the code example above, you would also have a button that would be something like
<button>onClick={(e) => setName('John Doe')}</button>to basically update the name state of whatever you are in, and then re-render the whole UI as need be
-
Function Component Lifecycle:
- Functional Components- are the fundamental building blocks for UI, and understanding their lifecycle is very crucial for managing behavior and state of components throughout their existence
- Generally, these functional components lack traditional lifecycle methods found in class components, similar functionalities can be achieved with hooks
- This includes things like
useState, useEffect, useReducer, & more - FOUR distinct functional component phases
- Mounting Phase
- Updating Phase
- Unmounting Phase
- Error Handling Phase
- Mounting Phase- Generally, this phase is whenever the functional component is actually initialized, and is prepared for rendering on the DOM
- Important steps include:
Initialization -> State Initialization -> Side Effects - Inside of
Initializationreact runs the function body of the functional component, setting up the initial structure and behavior of the component - Inside of
State Initializationwhich happens after regular initialization, here react basically uses theuseStatehook in order to initialize and declare state variables as well as the given functions inside of them - These variables also hold dynamically updating data and may cause the object to re-render
- Finally,
Side Effectsbasically include things like data fetching, subscriptions, or DOM manipulation using theuseEffecthook with an empty dependency array([]) - Updating Phase during this phase, react basically responds to changes in the component’s state or props by re-invoking the function body of the component, allowing for things like re-evaluation of the JSX and letting things like re-rendering occur, basically just runs the function again lowkey
- Unmounting Phase during this phase, react executes anything that involves cleanup operations when removing a component
- This would include things like cleaning up event listeners (buttons etc), subscriptions, and timers, essentially doing all the necessary HTML bullshit to unmount your object from the site
- It also frees up resources and what not so you do not get memory leaks
- Error Handling Phase- involves routing error to the nearest error boundary, which is the final phase of the actual functional component lifecycle
- Error Boundaries are special components that basically try and catch any given errors that might occur inside of their child components, letting you display a fallback UI or even one that showcases the error you made instead of crashing everything
-
Testing React Components:
-
Modern React Testing as Self-Driving car:
- Imagine a self-driving car, you do not pop the hood to test the engine, you take it for a ride to test how it would handle real-world conditions
- Similarly, modern react testing focuses on user experience, interactions, loading states, and asynchronous updates rather than internal mechanics
-
React’s New Features
- Concurrent rendering
- Automatic Batching
- Transitions
- Improves Suspense
-
Tests should generally focus on user-facing behavior, and simulating real interactions. Making sure that a UI outcome is validated and working as it needs to be
-
Modern tools like
React Testing Library (RTL), Jest, & Enzymeare recommended, although Enzyme is pretty old and deprecated -
Why testing changed in React- the newer react render basically allowed for concurrent rendering, meaning you can pause, resume, and batch updates for better performance in the rendering process
-
This means that updates are not always synchronous, DOM might not immediately reflect changes, and Tests that assume synchronous rendering can fail
-
Therefore, modern testing actually focuses on UI updates and avoids checking the DOM immediately after interactions
-
This allows for things like validation of user behavior, testing how a component responds to input, clicks, or network response
-
Also letting asynchronous rendering handle safely through utilities like
findBy & waitFor -
Another goal is to simulate real world usage by using libraries that mimic how users would interact with the browser.
-
The final goal of react is to ensures that components behave correctly under concurrency, testing components for loading and final states
-
Recommended Testing Libraries in React
- RTL- the industry standard for React component testing, is puts emphasis on user experience over internal logic, and automatically handles the act of concurrent rendering
- Jest- the most popular test runner and assertion library for react. It offers a complete testing environment with mocking and snapshots and also integrates well with RTL, including support for mock timers and network requests too
-
-
-
-
Lesson 1 Summary: Introduction to Function Components:
- Props principles include reusability, unidirectional data flow, customization, and composition.
- You can use the “useState” hook with an event to control a child component.
- You use component composition to combine smaller components to create a complex UI.
- Principles of component composition include abstraction, reusability, hierarchy, props and children, and higher-order components.
- State management allows you to manage data that can change over time within a component.
- The useState hook enables function components to manage the component’s state locally.
- You can use this syntax when using the useState hook:
- Call the “useState” function and pass in the initial state as a parameter.
- Assign the return value to a const array variable using a destructured array.
- The array has two values: the state name and the state name prefixed with the keyword “set.”
- The mounting phase initializes the component, sets up the initial state, and performs side effects.
- In the updating phase, React re-invokes the function body and re-evaluates JSX.
- In the unmounting phase, React executes cleanup operations when removing a component from the DOM.
==Array in React and Dom Manipulation
-
Working with Arrays in React Components:
- Array is basically a javascript data structure that is used to store multiple values inside of a single variable and can be declared with any object inside of two brackets separated by commas
- Inside of React, arrays are used to manage lists of data and are used to build dynamic and interactive user interfaces
- They also allow for things like letting their elements to be rendered by react components
- Below hand is a code example of how to store an array in react using State:
- They can also be constructed dynamically with something like a forloop or whatever it is that you like, this is because keep in mind, like python they are more so lists rather than arrays, although I assume they can not store different types of data
- Using array methods like
map, forEach, for...of loops, or indexbased traversal, you can use arrays in order to make very nice and interactive types of user interfaces, think of what I did the portal application with the dynamic text being “typed” out across the screen - The map method is generally used to iterate over an array, and return a new array of react elements as in the example above
- The for each method basically iterates over each element in the array and is able to then run a function on that element
- A for of loop is basically very similar to that of the for each loop, you iterate based on something and then run a function for it
- Index based looping basically allows you to use a traditional for-loop and index of each character in a given array item in order to access it and do whatever you would want to with it
- Rendering a list basically consists of you actually declaring it, and then you can basically use a map to go over each of the elements in the list and convert it from a JS string or whatever into an actual DOM element you can display to the screen
- Items in an array can equally be modified using the React State methods as well, especially if you are going to be displaying them
- The above hand is a code example of how to add and remove items inside of react syntax
-
Virtual DOM Manipulation in React:
-
-
The Document Object Model, or DOM is a tree-like interface for web browsers used to represent HTML documents
-
This allows for them to be easily rendered and allow for javascript to basically actually access and modify the content of the HTML Page
-
-
They are very useful, and have things like Nodes, Elements, Attributes, & Events all of which contribute to the style, rendering, and overall display of your website
-
You can really think of the DOM as the actual skeleton structure for your website, determining what elements you have to play with
-
The Virtual DOM is basically a framework that is utilized inside of React that Optimizes the performance of web applications
-
It is basically an abstraction of the actual DOM in memory, and is kept in sync with the real DOM by React’s Reconciliation Process, meaning things like dynamic interactions and updates become possible
-
-
Basically, whenever an initial rendering occurs, the react framework creates a copy of the DOM called the Virtual DOM
-
Then, whenever a new re-render or update happens inside of the dom structure, a new virtual dom is created.
-
The old virtual dom and new ones are then compared and updated using a Diffing Algorithm that identifies changes and showcases only the things needed to update
-
Then, a patch is applied from this diffing algorithm to the real DOM, showing the update in real time, with great efficiency
-
-
Virtual DOM Importance
- Speed Enhancement
- Simple Development
- Cross-Platform compatibility
- State Management
- Debugging and Testing
-
The virtual dom basically enhances the speed of the application by reducing the number of actual changes done to the real rendered DOM
-
This means that people can focus on writing declarative code without work of code messing with the DOM
-
This also means that the virtual dom can be used to render on multiple platforms between desktops and mobile devices
-
State management in tandem with the DOM allows for effective and real time updates during re-renders
-
You can also examine the virtual dom for bugs MUCH EASIER than you can the real DOM
-
Below is the difference between the Normal vs virtual DOM loading process, showcasing why the virtual dom is faster
-
-
-
-
Style in React (The Reading):
Inline styles
- The
<div>element has inline styles applied directly using the style attribute. - The styles are specified as a JavaScript object where the keys are CSS property names, and the values are the corresponding CSS property values
- Similarly, the
<p>element inside<div>has inline styles applied using the style attribute. - The above component will render a
<div>with a light blue background, padding, and border-radius. Inside the<div>,there’s a<p>element with white text color and a font size of 18 pixels, all styled using inline styles.
CSS modules
toggleMessage.module.css
- Import styles from ./toggleMessage.module.css;: This imports the CSS module toggleMessage.module.css as an object named styles. In CSS, a module typically refers to a file (usually with a.module.css extension) that contains a set of CSS rules scoped to a particular component or module in your application. These CSS rules are locally scoped to prevent unintended style conflicts between components.
- const [isVisible, setIsVisible] = useState(true);: This initializes a state variable isVisible using the useState hook. It represents whether the message paragraph should be visible or not, and it defaults to true.
- const toggleVisibility = () => {…};: This is a function that toggles the visibility of the message paragraph by updating the state variable isVisible when the button is clicked.
<p className={isVisible ? styles.message : ''}> This is a hidden message.</p>: This paragraph element displays the message. Its class name is conditionally set based on the value of isVisible. If isVisible is true, it applies the message class from the CSS module, otherwise, it applies an empty string, effectively removing any additional styles.
Styled components:
CSS can also be applied in React components using JavaScript objects, similar to the messageStyle object in the provided React component.
For example, in the following code there is one object with name messageStyle { color: ‘green’, fontSize: ‘18px’ } represents CSS properties for color and font size. It also has a conditional styling. For example, { display: isVisible ? ‘block’ : ‘none’ } that dynamically sets the display property based on the value of isVisible.
- The
-
Lesson 2 Summary:
- You use the array data structures often to store groups of items in a single variable.
- Two important array methods include:
- map(), which makes it easier to make new arrays by applying a function to each element
- forEach(), which runs a function on each array element without creating a new array
- The DOM allows access to and dynamically manipulates web documents’ content, structure, and style.
- React’s virtual DOM abstracts the actual DOM implemented in memory and keeps the virtual DOM in sync with the real DOM by React’s reconciliation process.
- React’s virtual DOM updates only the necessary parts of the DOM, improving the application’s performance, especially in scenarios where only specific components or elements need to be updated.
==Cheat Sheet
| Function Component with Array and DOM | Description | Code Example |
|---|---|---|
| Function Component with function keyword | Function component starts with function keyword along with name of the component and includes html tags within return. It also exports component name by default | 1. import React from ‘react’ 2. function Extra() { 3. return ( 4. <> 5. This is paragraph 6. </> 7. ) 8. } 9. export default Extra |
| Function Component with arrow function | Function component starts with variable type along with name of the component and includes html tags within return. It also exports component name by default | 1. import React from ‘react’ 2. const Extra = () => { 3. return ( 4. Extra 5. ) 6. } 7. export default Extra |
| Props in function component | Props can be sent from parent component as attribute along with child component | 1. import React from ‘react’ 2. import ChildComponent from ’./ChildComponent’ 3. function ParentComponent () { 4. let title=‘Project Manager’; 5. return ( 6. <> 7. 8. </> 9. ) 10. } 11. export default ParentComponent |
| Access Props within child function component | Props can be accessed easily within the child function component using props.variable_name | 1. import React from ‘react’ 2. const ChildComponent = (props) => { 3. return ( 4. <> 5. The title is {props.title} 6. </> 7. ) 8. } 9. export default ChildComponent |
| Event handling in class component | Events such as click event can be performed by calling function which is declared before return of function component | 1. import React from ‘react’ 2. const Extra = (props) => { 3. function show(){ 4. console.log(‘Show function’); 5. } 6. return ( 7. <> 8. The title is {props.title} 9. <button onClick={()=>show()}>Click Here 10. </> 11. ) 12. } 13. export default Extra |
| State management in function component | State management can be done easily with useState() hook | 1. import React, { useState } from ‘react’ 2. const StateManagement = () => { 3. const[name,setName]=useState(‘John’); 4. return ( 5. <> 6. State Management using useState7. The name is {name} 8. </> 9. ) 10. } 11. export default StateManagement |
| Array Declaration | Array can be declared in square brackets | 1. const names = [‘Alice’, ‘Bob’, ‘Charlie’]; |
| Stateful Array | Array can be declared using useState | 1. const [todos, setTodos] = useState([‘Learn React’, ‘Build Project’]); |
| Dynamically Constructed Arrays | Arrays can be constructed dynamically based on application logic or received data | 1. const numbers = []; 2. for (let i = 0; i < 10; i++) { 3. numbers.push(i); 4. } |
| Array map() method | The map() method is commonly used to iterate over each element of an array and return a new array of React elements | 1. const items = [‘Apple’, ‘Banana’, ‘Orange’]; 2. const itemList = items.map((item, index) => 3. return
|
| for…of Loop | You can use the for…of loop to iterate over the elements of an array: | 1. const items = [‘Apple’, ‘Banana’, ‘Orange’]; 2. for (const item of items) { 3. console.log(item); 4. } |
| Rendering a List of Items | You can render a list of items by mapping over an array and returning a JSX element for each item | 1. import React from ‘react’; 2. function ArrayComponent() { 3. const items = [‘Autumn’, ‘Spring’, ‘Summer’,‘Winter’]; 4. return ( 5. 6. Seasons Names7.
8. {items.map((item, index) => ( 9. 10. ))} 11. 12. 13. ); 14. } 15. export default ArrayComponent; |
| Adding and removing items in array | You can add or remove items from an array using state and React’s setState method | 1. import React, { useState } from ‘react’; 2. function MyComponent() { 3. const [items, setItems] = useState([‘Autumn’, ‘Spring’, ‘Winter’,’Summer’]); 4. const [inputValue, setInputValue] = useState(”); 5. const addItem = () => { 6. setItems([…items, inputValue]); 7. setInputValue(”); 8. }; 9. const removeItem = (index) => { 10. const newItems = […items]; 11. newItems.splice(index, 1); 12. setItems(newItems); 13. }; 14. return ( 15. 16. Fruits17.
18. {items.map((item, index) => ( 19. 23. ))} 24. 25. <input 26. type=“text” 27. value={inputValue} 28. onChange={(e) => setInputValue(e.target.value)} 29. /> 30. 31. 32. ); 33. } |
| Conditional rendering using ternary operator | You can conditionally render components based on the content of an array | 1. import React, { useState } from ‘react’; 2. function ArrayComponent() { 3. const [items, setItems] = useState([‘React JS’,‘Vue JS’,‘Angular JS’,‘Vanilla JS’]); 4. return ( 5. 6. Front End Languages7. {items.length > 0 ? ( 8.
9. {items.map((item, index) => ( 10. 11. ))} 12. 13. ) : ( 14. No Front End language is available 15. )} 16. 17. ); 18. } 19. export default ArrayComponent; |
| inline style in react | Inline style can be applied within the tag as an attribute within double curly braces | 1. import React from ‘react’; 2. function MyComponent() { 3. return ( 4. <div style={{ backgroundColor: ‘lightblue’, padding: ‘20px’, borderRadius: ‘5px’ }}> 5. <p style={{ color: ‘white’, fontSize: ‘18px’ }}>This is a paragraph with inline styles. 6. 7. ); 8. } 9. export default MyComponent; |
| Style using object | Style can be applied as an object like inline style | 1. import React, { useState } from ‘react’; 2. function ToggleMessage() { 3. const [isVisible, setIsVisible] = useState(true); 4. const toggleVisibility = () => { 5. setIsVisible(!isVisible); 6. }; 7. const messageStyle = { 8. display: isVisible ? ‘block’ : ‘none’, 9. color: ‘green’, 10. fontSize: ‘18px’, 11. marginTop: ‘10px’ 12. }; 13. return ( 14. 15. Toggle Message16. 19. This is a hidden message. 20. 21. ); 22. } |
==Glossary
| Term | Definition |
|---|---|
| Abstraction principle | A principle that provides a way to make reusable components that encapsulate UI features. |
| Array | A data structure in JavaScript used to store multiple values in a single variable. |
| Array destructuring | A feature that allows you to extract values from an array and assign them to individual variables. |
| Array literal | A syntax in JavaScript for creating arrays. It allows you to define an array by enclosing a comma-separated list of elements within square brackets. |
| Attributes | Provide additional information about elements. They can specify properties, styles, or behavior. |
| Component composition | A combination of multiple smaller components to create complex functionality. |
| Document object model (DOM) | An interface for web pages and documents used to represent an HTML structure as a tree-like structure. |
| Elements | Are the building blocks of HTML documents. |
| forEach() | A method that iterates over each element of an array and executes a callback function. |
| Hierarchy principle | A principle that allows you to arrange components in a hierarchy, with parent and child components. |
| Higher-order component | A function that allows you to add components’ features, such as state management or logic, without modifying its implementation. |
| Hook | A function that enables you to reuse code logic across components without changing component hierarchy or introducing unnecessary nesting. |
| Initialization | A step in which React runs the function body of the functional component, setting up the initial structure and behavior of the component. |
| map() | A method commonly used to iterate over each element of an array and return a new array of React elements. |
| Mounting phase | A functional component lifecycle phase in which React initializes the functional component, preparing it for rendering on the DOM. |
| Props Default | Is default value for props using defaultProps. This ensures that if a prop is not provided, the component will still render with the default value, enhancing predictability and robustness in component behavior. |
| Properties (props) | A fundamental concept in React for passing data from parent to child components. They enable communication and customization between different parts of a React application. |
| Rendering Array | Involves dynamically generating and displaying elements based on the contents of the array. This is commonly done using JavaScript’s map() function to iterate over the array and generate React elements for each item. |
| Reuse principle | A principle to reuse chunks of code, making it easier to organize and maintain. |
| Side effects | A step that includes data fetching, subscriptions, or DOM manipulation using the ‘useEffect’ hook with an empty dependency array. |
| State | The condition of a component at a specific time and it holds information that influences the object’s behavior and renders it based on that information. |
| State management | Involves handling and updating the data over time, allowing components to dynamically change their appearance and behavior in response to user actions or other events. |
| State initialization | A step in which React utilizes the ‘useState’ hook to declare and initialize state variables within the component. |
| Updating phase | A functional component lifecycle phase in which React responds to changes in the component’s state or props by re-invoking the function body of the component. |
| Unmounting phase | A functional component lifecycle phase in which React executes cleanup operations when removing a component from the DOM. |
| useState hook | A built-in React Hook that allows functional components to manage state. It provides a way to declare state variables and update them within a functional component. When the state changes, React automatically re-renders the component to reflect the updated state. |
| Virtual DOM | An abstraction of the actual DOM implemented in memory and is kept in sync with the real DOM by React’s reconciliation process. |




























