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}