What is declarative?
This command is a tool which install transpiling webpack and babel for us.
Babel transpiles ES6 to ES5 (jsx to javascript) to be readable by browsers.
JSX is JavaScript XML.
After the installation we have the following React structure folders
The src folder contains the following files.
Run the app in browser by typing in terminal use the command npm start . It will show the default app we created in the browser on port 3000.
If you change the contents of the App.js file in the src folder, you will see the changes in browser on port 3000.
App.js is the root of our app that combine all components together. Then we connect App.js to index.js to show our app in the index.html file to view in browser.
To run the server in the browser by npm startcommand, we must be at the root folder I mean the main folder of our app. If not use the command cd first-app to go to root folder then type the command in terminal.
To install packages and modules manually
It is used for module packaging, development and production.
Webpack bundles webpack-dev-server for development, webpack for production and webpack CLI that contains necessary commands to be used in command prompt or terminal.
Use the command npm install webpack webpack-dev-server webpack-cli --save to install all three at one time
babel is a JavaScript compiler that convert JSX into javascript to be readable by browsers.
babel-loader is for jsx files, babel-preset-react is for updating browsers automatically and ES6 uses babel-preset-env
webpack.config.js is used to configure webpack, it is the entry point of our app, it sets the development port, it adds plugins and loaders for different file types.
Add the following codes to configure webpack in webpack.config.json
Now add the following code in index.html file.
Now we are importing the script source file of index_bundel.js into index.html file to Use fileHtmlWeb-packPlugin plugin from bundeled file which scale our app to be responsive to differnt devices.
It is entry point of our app to render our components
Add the following code into App.js.
Now we import App.jsfile (component) into root directory (index.js) file.
Run the server and see the result by typing in terminal the command npm start
Now you can create a bundled file named index_bundle.js which bundle all file into a file and merge them to have it with other files of webpage to load the app at once. For bundeling type the command npm run build in terminal to merge the file into one file (index_bundle.js).
ReactJS: Focused on web development, ReactJS facilitates the creation and management of dynamic user interfaces for web pages and applications. It runs directly in web browsers, allowing developers to craft engaging and interactive UIs utilizing JavaScript.
React Native is expressly crafted for the development of mobile applications, empowering the generation of native applications for mobile devices through the utilization of JavaScript and React. Its focus extends to mobile operating systems like iOS and Android, facilitating a cohesive codebase for both platforms.
ReactJS ses CSS for styling, which can be applied through external stylesheets, inline styles, or CSS-in-JS libraries. React Native: Employs a styling system that resembles CSS but actually uses JavaScript objects to style components. This approach is more in line with how React itself handles UI logic.
There are two types of components in React:
Example 1: Using jsx (Javascript and XML)
Functional Component without Props
Example 2:
Functional Component with Props
Example 3:
Functional Component with Destructuring Props
Username: {username}
Age: {age}
Example 1:
Class Component without State
Example 2:
Class Component with State
Count: {this.state.count}
Example 3:
Class Component with Lifecycle Method
Component with lifecycle methods
; } } // Usage const App = () => { returnProps:
Parent and child component are usually in separate .js or .jsx file
Parent component or file collects all child components in one place or file.
Each child components are written in a separate .js files
Example 1:
Functional Component without Props
Hello, Guest!
; }; Example 2:
Functional Component with Props
Hello, {props.name}!
; }; Example 3:
Class Component with Props and State
Welcome, {this.props.name}!
; } } Example 1:
Class Component with State
Count: {this.state.count}
Example 2:
Functional Component with State using useState Hook
The light is {isOn ? 'on' : 'off'}.
Example 3:
Class Component with Form Input and Controlled Component
You typed: {this.state.inputValue}
In JSX, you can specify event handlers by passing functions as props. Event names are written in camelCase, similar to their DOM counterparts.
To pass extra data to an event handler, use arrow functions or the bind method to generate a new function.
We can prevent the default behavior of an event using the preventDefault method available on the event object.
React's event system also supports stopping event propagation using the stopPropagation method.
React provides synthetic events that are similar to native DOM events but with some differences. They are automatically cleaned up when the component is unmounted to avoid memory leaks.
In above example, event is a synthetic event object that wraps the native browser event.
You can conditionally attach event handlers based on certain conditions.
In above example, event is a synthetic event object that wraps the native browser event.
In JSX, we can use a standard JavaScriptif statement to conditionally render a component or content.
In JSX, we can use a ternary operator to conditionally render a component or content.
This approach keeps the JSX code cleaner and more readable, especially for smaller conditional blocks.
We can use the logicalAND (&&) operator to conditionally render elements based on a truthy value.
This approach is concise and effective, especially when you only need to render a single component based on a condition.
We can use the logicalOR (||) operator to conditionally render elements based on a falsy value.
This approach is concise and effective, especially when you only need to render a single component based on a condition.
This approach allows for more flexibility and enables you to nest conditional rendering within other JSX elements.
We can use inline functions to conditionally render a component or content based on more complex conditions or logic.
We can use the switch statement to conditionally render a component or content based on a value.
For more complex scenarios with multiple conditions, use a switch statement inside the render() method.
This approach is suitable when you have several different cases to handle, making the code more organized and readable.
We have a state variable isLoggedIn to track the user's authentication status.
We conditionally render either the WelcomeMessage component if the user is logged in or the LoginForm component if the user is not logged in.
When the user logs in successfully, the handleLogin function is called to update the isLoggedIn state, triggering a re-render to display the WelcomeMessage component.
Conditional rendering in React provides a powerful mechanism for building dynamic and interactive user interfaces, allowing you to adapt the UI based on different application states and user interactions.
Basic lists render a collection of items without needing to maintain state or handle complex logic.
Dynamic lists use state to manage the collection of items, allowing for dynamic addition, removal, or modification of list items.
Unique keys are identifiers assigned to individual items within a list, aiding React in recognizing items during the process of re-rendering
In React, forms are used to collect and process user input. There are several types of forms and various ways to handle form submission and input changes.
Utilizing different types of forms in React will create powerful and interactive user interfaces for collecting user input and processing data.
It is better to choose the right type of form that best fits the application's requirements.
Uncontrolled forms allow the DOM to maintain the form data. You can still access form data using a ref, but React does not control the form data.
Controlled forms use React state to control the form data. Each form input element has an associated state value and an event handler to update that state value.
Formik is a library for building forms in React. It simplifies form management by handling form state, validation, and submission.
React Hook Form is another library for building forms in React. It focuses on performance and flexibility by utilizing React hooks.
Mounting:
Mounting is the phase in which a component's instance(component) is created and integrated into the DOM.
This phase includes the following lifecycle methods:
This stage happens when a component undergoes re-rendering as a result of alterations in its props or state.
Updating phase occurs when a component’s props or state changes, prompting a re-render. The methods involved are:
Same as in mounting phase, used for state updates in response to prop changes.
Invoked again to re-render the component.
Unmounting occurs when a component is removed from the DOM.
There's only one lifecycle method for this phase:
First,create React application using Create React App as below.
Then Install React Routeras below.
Create a some simple components to navigate between.
For instance, Home.js, About.js, and Contact.js.
Then create an App.js component to have all the pages to be called in one place
In App.js, the <Routes> component is used as a container for multiple <Route> components.
Each <Route>defines a mapping between a path and a component.
When the URL matches the path, React Router renders the specified component.
Layout is always rendered, and depending on the URL, Home, About, or Contact is rendered within Layout.
To create an applications that requires a consistent layout (e.g., shared headers or footers), nested routes allow you to define a common structure that wraps other views.
Create a Layout component (Layout.js) that includes navigation links and an <Outlet> where child routes are rendered.
In above we are incorporating the layout into routing by making it a parent route.
In above approach keeps the navigation consistent across different pages, and enhancing the user experience.
An application with a nested structure: a main layout that contains a navbar, and two main sections, "Dashboard" and "Settings", each with their own sub-pages.
Layout.js uses an Outlet to render either the "Dashboard" or "Settings" component, while Dashboard.js can further render nested components, such as specific views or widgets, into its own Outlet.
Define dynamic segments in the path by prefixing a segment of the path with : (colon).
For instance, a route for individual blog posts might look like this:
Protected routes are routes that require some form of authentication or authorization.
To implement it, create a component that checks for user authentication and either renders the requested component or redirects to a login page.
In below example demonstrates an authentication check.
If auth.user is not present, it redirects to the /login page.
Otherwise, it renders the children components, to access to the protected route.
Redirects will send users to a different page (The path that originally is not requested).
For instance redirecting from old URLs to new ones or redirecting unauthenticated users away from protected routes.
To implement a redirect in React Router,
use the <Navigate> component with the replace prop to prevent the original route from being added to the history stack:
In above syntax, it automatically redirect anyone who navigates to /old-path to /new-path instead.
The Outlet and layout components in React Router are crucial for creating complex applications with nested routes
The developer can build a consistent build a consistent structure across various pages.
Outlet is a component provided by React Router that serves as a placeholder for rendering child routes.
It is used within parent route components to specify where child routes should be rendered.
This mechanism is particularly useful for creating nested routes.
In your main application file (App.js)
we define routes using Layout as a wrapper for other content.
A layout component in React Router defines a structure that should be present across multiple routes.(A layout component in React Router is used to define a common structure (include headers, footers, sidebars, or any other persistent UI elements) that should be present across multiple routes.
The layout component typically wraps the Outlet component till nested routes are rendered within the context of this structure.
Below are the primary categories of Hooks in React.
Count: {count}
React Fragments enables the bundling of multiple child elements without the need for additional nodes in the DOM.
For this purpose use <React.Fragment> or its shorthand syntax <> ... </>
In above example, MyComponent returns two <div> elements wrapped in a React.Fragment.
The grouping does not add an extra layer to the DOM.
It keeps the structure clean and efficient.
Fragments can accept keys, which is useful when mapping a collection to an array of elements, making them quite handy.
This is a simpler and modern way to consume or use context
It is available in functional components.
It takes the context object itself as an argument and returns the current context value.
The Context API in React is a tool for:
handling global state
and transmitting data across the component hierarchy.
Nevertheless, it doesn't used for all scenarios of state management.
Functional or component separation or decomposition: Break down the UI into smaller, reusable components(function) that each have a single responsibility.
This promotes code reuse and makes components easier to understand and maintain.
This is the most common type of boundary.
Container components are responsible for data fetching and state management.
Presentational components do focus on rendering UI.
This maintains a clear separation of data and presentation logic.
Local Component State:
Use local state within components for managing UI-specific state that doesn't need to be shared with other components.
Use global State Management with the use of state management libraries like Redux, Context API, or Recoil for managing
global application state that can be accessed across multiple components.
This centralizes state logic and avoid using prop.
Dynamic Imports: Employ dynamic import() to partition your code into smaller units that are fetched as needed.
This approach enhances the initial page loading speed by only loading the code essential for the present view.
React.lazy() and Suspense:
React.lazy() and Suspense are two features in React used to do code splitting and improving the performance of your application by loading components asynchronously .
React.lazy() is a function that dynamically import a React component(loads only components that are needed to load th app).
It significantly improve the initial loading time of the application(especially for large applications that has lots of components).
Think we have a component named MyComponent that you want to import lazily:
Import it lazily in another component as follows:
In the example above, we see Suspense wraps the lazy-loaded component <LazyLoadedComponent >.
The fallback prop specifies what should be rendered while the component is loading.
/p>
While the LazyLoadedComponent is being fetched and loaded asynchronously, We see a loading indicator instead of a blank screen, providing a better user experience.
Error Boundaries: Use error boundaries to handle errors (catch JavaScript errors) that occur in your application.
It prevents the application from crashing when an unexpected error occurs.
Error boundaries in React catch JavaScript errors occurring in their child component tree.
Instead of letting these errors disrupt the user experience, error boundaries log them and display a backup UI.
These boundaries capture errors during rendering, lifecycle methods, and constructors of all components below them.
Context Providers:
Use Context API to pass data or functions down through the component tree without manually passing props at each level.
Use or define context providers at appropriate boundaries to encapsulate related state or behavior.
API Endpoints:
Create or define clear boundaries between client-side and server-side logic.
Use API endpoints to communicate between the frontend and backend parts of your application, ensuring separation of concerns and security.
Loading...
; }; }An error occurred: {error.message}
; } returnPlease log in to view this part of the application.
; }; }Hello, {name}!
; }; // Wrap MyComponent with withLogging HOC const EnhancedComponent = withLogging(MyComponent); // Usage const App = () => { returnWe define the withLogging HOC, which takes a WrappedComponent as an argument.
Inside the HOC, we return a new component that renders the WrappedComponent and logs its props before rendering.
We then wrap our MyComponent with the withLogging HOC to create the EnhancedComponent.
When EnhancedComponent is rendered, it logs the props before rendering MyComponent.
Use the above (example 6) to enhance any component
HOCs introduce an additional layer of component abstraction, which can sometimes make the component hierarchy more challenging to understand.
HOCs do not modify the original component. Instead, they create a new component with enhanced functionality, which may affect component identity and lifecycle methods.
HOCs are a powerful tool, but overuse can lead to code complexity and reduced readability. Use them judiciously and consider alternative patterns such as Render Props or Hooks when appropriate.
Overall, Higher-Order Components are a valuable tool in the React developer's toolkit for enhancing component functionality, promoting code reuse, and improving application architecture.
HOCs are like kind of wrappers for the components to add additional functionalities (like checking for login, handling errors, loading data) without making changes to the original components. It is helpful in reusing code and keeping components organized.
It is maintained by Facebook, stands as a JavaScript testing framework, easy to use with rapidity, and robust capabilities. It offers features like snapshot testing and mocking.
React Testing Library, a testing utility designed for React.
It mirrors user interaction with the application.
It provides a user-friendly and simple API for querying and interacting with components.
React Testing Library is a powerful tool for testing React components.
It tests that components behave correctly.
React Testing Library integrates with popular testing frameworks like Jest.
We can write and run tests within our existing testing setup.
For integration testing, we use tools like Cypress or testing library's testing frameworks.
In React, there are several ways to style components. Here are some common methods to style the React App.
W can apply styles directly within the JSX using JavaScript objects.
We can create separate CSS files and import them into your components.
CSS Modules allow scoped styling for components.
Styled Components offer a way to write CSS directly within your JavaScript files.
There are other libraries similar to Styled Components that allow you to use CSS-in-JS, such as Emotion.
These libraries let you write CSS directly in your JavaScript, providing dynamic styling capabilities.
A utility-first CSS framework that can be used in React for rapidly building custom designs by composing utility classes.
SASS/SCSS is a scripting language that pre-processes code before it's converted into CSS. It offers enhanced capabilities compared to standard CSS, including features like variables, nested rules, mixins, and additional functionalities
We can dynamically change styles based on props or state.
Each of these methods has its own set of advantages.
Inline styles and CSS-in-JS libraries like Styled Components or Emotion are great for components that require dynamic styles based on props or state.
CSS, SASS/SCSS, and CSS Modules are excellent for more static, global styles.
Tailwind CSS is favored for its utility-first approach and rapid prototyping capabilities.
The choice often depends on the project requirements, scalability needs, and developer preference.
The Fetch API comes integrated into contemporary browsers, offering a straightforward and robust mechanism for asynchronously retrieving resources or data.
{JSON.stringify(data, null, 2)}}
A popular HTTP client library to make AJAX requests in JavaScript.
{JSON.stringify(data, null, 2)}}
Use of the useEffect hook in combination with the Fetch API for data fetching.
{JSON.stringify(data, null, 2)}}
Reducers (function) specify how the application's state changes in response to actions sent to the store.
Demonstrating in a todo application context in a place:
create actions, reducers, and a store .
How to use Redux with React:
Redux provides a robust solution for managing global state in complex applications.
It makes state mutations predictable and easier to manage.
In React, patterns are commonly used approaches or strategies for structuring code, managing state, handling data flow, and improving code organization and reusability.
Also known as the "Smart-Dumb Component" pattern, this pattern separates components into two categories: container components and presentational components. Container components are responsible for data fetching, state management, and business logic. Presentational components are concerned only with UI rendering and receive data via props.
{data}
}Container components handle data fetching and state management using hooks like useState and useEffect.
Presentational components receive data via props and are focused solely on rendering UI based on the provided data.
The Render Props pattern involves passing a function as a prop to a component, allowing the component to render content using the function's return value.
It promotes code reuse by enabling components to share behavior and logic through a common interface.
Hello, World!
)} /> ); }; export default App;The MyComponentWithRenderProp component receives a render prop, which is a function that returns the content to be rendered.
By passing different functions to the render prop, you can control what content is rendered by the component, allowing for flexible and reusable components.
Higher-Order Components are functions that accept a component as input and return a new component with enhanced functionality.
They enable code reuse and cross-cutting concerns such as logging, authentication, or data fetching.
The withHOC function takes a component as input and returns a new component that enhances the functionality of the input component.
The enhanced component can include additional props, state, or behavior provided by the HOC.
Applying patterns can improve code organization, reusability, and maintainability in your React applications.
React performance optimization is crucial for ensuring smooth and efficient rendering of your applications, especially as they grow in complexity.
Memoization involves caching the outcomes of costly function invocations and retrieving them when identical inputs reappear.
In React, you have the option to employ either the React.memo Higher-Order Component or the useMemo hook for memoizing components or values, respectively.
useMemo is a React hook that returns a memoized version of a function.
It reduces unnecessary re-renders of components or recomputation of values.
It improves rendering performance by avoiding redundant work.
Virtualization is a technique for rendering large lists or grids efficiently by only rendering the items that are currently visible on the screen.
Libraries like React Virtualized or React Window provide components for virtualizing lists and grids.
It improves performance and reduces memory consumption when rendering large datasets
It enables smooth scrolling and interaction with large lists or grids.
Code splitting involves breaking down your application into smaller bundles or chunks that are loaded asynchronously.
React.lazy and Suspense enable you to load components lazily, improving initial loading time and reducing the size of the main bundle.
It reduces initial load time by loading only the necessary code for the current view.
It improves perceived performance by displaying loading indicators during component loading.
PureComponent and shouldComponentUpdate are strategies aimed at enhancing rendering performance by avoiding unnecessary re-renders of components.
PureComponent conducts a shallow examination of props and state to ascertain if a component necessitates an update.
shouldComponentUpdate affords the flexibility to tailor the criteria dictating when a component should undergo an update.
It reduces unnecessary re-renders of components, improving rendering performance.
It enhances overall application performance by minimizing unnecessary work in the render cycle.
React provides various performance tools for measuring and optimizing the performance of your applications.
Tools like React DevTools, Chrome DevTools, and performance monitoring libraries help identify performance bottlenecks and optimize rendering performance.
Use React DevTools to inspect component hierarchies, measure component render times, and identify wasted renders.
Provides insights into component performance and rendering bottlenecks.
Enables targeted optimizations to improve overall application performance.
These techniques and tools, you can optimize the performance of your React applications, ensuring smooth rendering and improved user experience, even as your application grows in complexity.
Remember to measure performance regularly and prioritize optimizations based on profiling data and user feedback.
Name: {data.user.name}
Email: {data.user.email}
To create a PWA with React, you can start with Create React App (CRA), which includes a service worker and a web app manifest by default, providing a good starting point for developing PWAs.
Step 1: Set Up React App
Step 2: Make Your React App a PWA
Service Worker: The default service worker in CRA only works in production build. You can customize it for more advanced offline capabilities. Ensure the service worker is registered in your index.js:
Web App Manifest: Customize the public/manifest.json file with details about your app. This file defines how your app appears on the user's home screen and how it can be launched.
HTTPS is essential for PWAs to guarantee a secure connection. During development, the Create React App development server automatically utilizes HTTPS. When deploying to production, make sure your hosting provider offers support for HTTPS.
Add Offline Capabilities: This is where the power of service workers comes in. You can customize the service worker script to cache the application shell (HTML, CSS, JavaScript files) and app data for offline use.
Deploy Your App: When you're ready, build your app for production
Deploy your app to a secure web server that supports HTTPS. Many hosting platforms like Netlify, Vercel, and GitHub Pages offer simple, secure hosting for PWAs.
Lighthouse: Use Google's Lighthouse tool to audit your PWA. It provides insights into performance, accessibility, progressive web app metrics, SEO, and more.
Manual Testing: Test your PWA on various devices and browsers to ensure it meets your expectations in terms of performance, responsiveness, and functionality.
PWAs with React combine the best of web and mobile app features. With service workers for offline work and background syncing, a manifest file for add-to-home-screen and full-screen capabilities, and push notifications for user re-engagement, PWAs can provide a user experience comparable to native apps while remaining lightweight and accessible through a browser.
The choice of strategy depends on factors like your project's requirements, the size of your team, and how independently you want to deploy each part of your application.
In this approach, micro frontends are integrated during the build process. Webpack Module Federation is a popular choice for this, allowing a JavaScript application to dynamically load code from another application.
webpack.config.js in App 1:
webpack.config.js in App 2:
Run-time integration involves loading micro frontends at runtime. iFrames and Web Components can encapsulate micro frontends, ensuring independence in terms of styling and JavaScript execution.
index.html in the main app
In micro frontend:
This method involves dynamically loading micro frontends as JavaScript applications at runtime. This could be done through script tags, SystemJS, or import maps.
Example with dynamic script loading:
Styling Isolation: Avoiding CSS leaks and ensuring consistent styling across different micro frontends.
State Management: Managing application state across micro frontends can be challenging.
Performance: Extra care must be taken to manage the size of the application and loading times, especially with run-time integration.
Routing: Coordinating routing between micro frontends to provide a seamless user experience.
React Native is an open-source framework for building native apps for iOS, Android, and the web. React Native is built on top of JavaScript, and runs on top of the React JavaScript library.
React Native is a tool made by Facebook using JavaScript. Even though it's related to React.js, it's a bit different.
React Native is a great tool for making apps that work on different types of phones using React's building blocks.
It's important for developers to know these differences if they want to build websites or mobile apps with React.
Even though React.js and React Native have similar ideas and ways of writing code, they're meant for different things and work in different ways.
>React.js (React): Targets web browsers and web applications.
React Native: Targets native mobile platforms like iOS and Android.React.js: Uses HTML, CSS, and virtual DOM for rendering UI components in web browsers.
React Native: Uses native UI components provided by the respective mobile platforms (UIKit for iOS, Android SDK for Android).
React.js: Developed and tested in web browsers.
React Native: Developed using React Native CLI or Expo CLI and tested on simulators/emulators or real devices.
React.js: Uses CSS for styling web components.
React Native: Uses StyleSheet API for styling components with JavaScript, which gets converted into native styles.
React.js: Accesses browser APIs like DOM, localStorage, etc.
React Native: Accesses native device APIs like Camera, Geolocation, etc., using JavaScript interfaces provided by React Native.
React.js: Developers use browser-based developer tools like React DevTools for debugging and inspecting components.
React Native: Developers use platform-specific debugging tools like Xcode for iOS and Android Studio for Android.
The syntax in React Native is similar to React.js, with some platform-specific components and APIs for mobile development. Here's a simple example of a React Native component:
While React.js and React Native share some common concepts, there are also topics specific to each:
Contributing to React open source means getting involved in making React and its related projects better.
Here's how you can help out how you can contribute to React open source:
By helping with React, you can make it even better, connect with other developers, and be part of a big community.