diff --git a/docs/react/_category_.json b/docs/react/_category_.json deleted file mode 100644 index 6f7bf7453..000000000 --- a/docs/react/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "React", - "position": 22, - "link": { - "type": "generated-index", - "description": "React is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies." - } - } \ No newline at end of file diff --git a/docs/react/advanced-usage/_category_.json b/docs/react/advanced-usage/_category_.json deleted file mode 100644 index 3628975e8..000000000 --- a/docs/react/advanced-usage/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced Usage", - "position": 10, - "link": { - "type": "generated-index", - "description": "5 minutes to learn the most important RoadMap for React Mastery." - } - } \ No newline at end of file diff --git a/docs/react/advanced-usage/advanced-configuration.md b/docs/react/advanced-usage/advanced-configuration.md deleted file mode 100644 index f15ab9223..000000000 --- a/docs/react/advanced-usage/advanced-configuration.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -id: advanced-configuration -title: Advanced Configuration -sidebar_label: Advanced Configuration -sidebar_position: 4 -tags: [Create React App, Advanced Configuration, Environment Variables, Webpack, Babel, CRACO, react-scripts, Custom Scripts, Ejectify, Custom Templates] -keywords: [create react app, advanced configuration, environment variables, webpack, babel, craco, react-scripts, custom scripts, ejectify, custom templates] -description: Learn how to customize and fine-tune your React projects with advanced configuration options in Create React App. Discover powerful features and alternatives to ejecting that will help you take control of your development environment. ---- -In Create React App, you have the power to customize various development and production settings using environment variables. These options allow you to control the behavior of your React application without diving into complex configurations. Let's take a closer look at each setting in a handy table format: - -| Variable | Development | Production | Usage | -| :------------------------ | :---------: | :--------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| BROWSER | ✅ Used | 🚫 Ignored | Override the default system browser that Create React App opens during development. You can specify a specific browser or set it to `none` to disable browser opening. You can even use a custom Node.js script for launching the browser with additional arguments from `npm start`. | -| BROWSER_ARGS | ✅ Used | 🚫 Ignored | Pass additional arguments to the browser instance when `BROWSER` is specified. Multiple arguments are supported, separated by spaces. | -| HOST | ✅ Used | 🚫 Ignored | Specify a custom host for the development web server. By default, it binds to all available hostnames on the device. | -| PORT | ✅ Used | 🚫 Ignored | Set a custom port for the development web server. By default, it listens on port 3000 or finds the next available port if 3000 is in use. | -| HTTPS | ✅ Used | 🚫 Ignored | Run the development server in `https` mode by setting this variable to `true`. | -| WDS_SOCKET_HOST | ✅ Used | 🚫 Ignored | Specify a custom WebSocket hostname for hot module reloading in the development server. Useful when working on multiple Create React App projects simultaneously. | -| WDS_SOCKET_PATH | ✅ Used | 🚫 Ignored | Set a custom WebSocket path for hot module reloading in the development server. Helpful when working on multiple Create React App projects simultaneously. | -| WDS_SOCKET_PORT | ✅ Used | 🚫 Ignored | Use a custom WebSocket port for hot module reloading in the development server. Useful for working on multiple Create React App projects simultaneously. | -| PUBLIC_URL | ✅ Used | ✅ Used | Force assets to be referenced verbatim to the provided URL (including hostname). Useful when using a CDN to host your application. This variable overrides the default assumption of your app's hosting location specified in `package.json` (`homepage`). | -| BUILD_PATH | 🚫 Ignored | ✅ Used | Specify a new path for Create React App to output compiled assets during the production build. By default, assets are output to `/build` directory adjacent to your `/src`. | -| CI | ✅ Used | ✅ Used | Treat warnings as build failures and make the test runner non-watching when `true`. Most Continuous Integration (CI) environments set this flag by default. | -| REACT_EDITOR | ✅ Used | 🚫 Ignored | Override the automatic editor detection in development. When your app crashes, you'll see an error overlay with a clickable stack trace. Clicking it opens the relevant source file based on running processes. You can set this variable to your editor's bin folder's path or `none` to disable it. | -| CHOKIDAR_USEPOLLING | ✅ Used | 🚫 Ignored | Run the watcher in polling mode (`true`) if `npm start` isn't detecting changes. Useful inside virtual machines (VMs). | -| GENERATE_SOURCEMAP | 🚫 Ignored | ✅ Used | Enable (`true`) or disable (`false`) source maps generation during production build. Disabling source maps can resolve Out of Memory (OOM) issues on some smaller machines. | -| INLINE_RUNTIME_CHUNK | 🚫 Ignored | ✅ Used | Embed (`true`) or import as usual (`false`) the runtime script into `index.html` during production build. Use this when dealing with Content Security Policy (CSP) restrictions. | -| IMAGE_INLINE_SIZE_LIMIT | ✅ Used | ✅ Used | Control the size limit (in bytes) for images that will be inlined in the CSS or JS build artifact as data URI in base64. Set to `0` to disable image inlining. | -| FAST_REFRESH | ✅ Used | 🚫 Ignored | Enable (`true`) or disable (`false`) experimental Fast Refresh support. Fast Refresh allows tweaking components in real-time without reloading the page. | -| TSC_COMPILE_ON_ERROR | ✅ Used | ✅ Used | Allow running and building TypeScript projects even with TypeScript type check errors. Errors are displayed as warnings in the terminal and/or browser console. | -| ESLINT_NO_DEV_ERRORS | ✅ Used | 🚫 Ignored | Convert ESLint errors to warnings during development, hiding them from the error overlay. | -| DISABLE_ESLINT_PLUGIN | ✅ Used | ✅ Used | Completely disable the [eslint-webpack-plugin](https://github.com/webpack-contrib/eslint-webpack-plugin). | -| DISABLE_NEW_JSX_TRANSFORM | ✅ Used | ✅ Used | Disable (`true`) the new JSX transform introduced in React 17 and backported to React 16.14.0, 15.7.0, and 0.14.10. New projects have this enabled by default, but you may need to disable it in existing projects if you can't upgrade React. | - -Remember to experiment with these configurations, as it allows you to tailor your React application according to your specific requirements. - -## Advanced Configuration in Create React App - -Welcome to the world of advanced configurations in Create React App! 🚀 In this guide, we'll dive deeper into the powerful features and options available to fine-tune your React projects. Don't worry; we'll make sure it's easy to understand, even for beginners! - -## What is Create React App? - -For those who are new to Create React App (CRA), it's a fantastic tool that helps you kickstart your React projects without getting bogged down in complex setup processes. CRA abstracts away the configuration, allowing you to focus on building amazing React applications right from the get-go. - -## Customizing the Configuration - -CRA provides a way to customize its configuration without ejecting your project. Ejecting means you'd have to deal with all the build tools and configurations yourself, which can be overwhelming for beginners. So, let's look at how to customize the configuration while staying within the comfort zone of CRA. - -### Environment Variables - -Environment variables are super handy for managing various settings in your app. By default, CRA supports `.env` files, but you can create environment-specific files like `.env.development`, `.env.production`, etc. - -```bash -# .env.development -REACT_APP_API_URL="https://api.dev.example.com" -``` - -Now, you can access the variable like this: - -```javascript -const apiUrl = process.env.REACT_APP_API_URL; -``` - -### Adding Webpack Plugins - -Webpack is the magic behind CRA, and you can extend it with plugins. For example, let's add the "Bundle Analyzer" plugin to visualize your bundle's size: - -```javascript -// In your react-scripts version 5.0.0+ or higher, you can use the following syntax in the 'webpack.config.js' -const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); - -// Inside your 'webpack.config.js' module.exports object, add this plugin to the 'plugins' array -module.exports = { - // ... other config options ... - plugins: [ - // ... other plugins ... - new BundleAnalyzerPlugin(), - ], -}; -``` - -### Rewriting the Webpack Config - -Need more control over the Webpack configuration? CRA offers a simple way to extend the config directly: - -```javascript -// In your react-scripts version 4.0.0+ or higher, you can use the following syntax in the 'craco.config.js' -module.exports = { - webpack: { - configure: (webpackConfig) => { - // Add your custom webpack config here - webpackConfig.optimization.minimize = true; - return webpackConfig; - }, - }, -}; -``` - -### Adding Babel Plugins - -To further enhance your app's capabilities, you can add Babel plugins to transform your code. For example, let's add the "transform-class-properties" plugin: - -```bash -npm install --save-dev @babel/plugin-proposal-class-properties -``` - -Then, create a `.babelrc` file in the root of your project: - -```json -{ - "plugins": ["@babel/plugin-proposal-class-properties"] -} -``` - -Now you can use class properties in your components: - -```javascript -class MyClassComponent extends React.Component { - state = { - count: 0, - }; - - handleClick = () => { - this.setState((prevState) => ({ count: prevState.count + 1 })); - }; -} -``` - -## Conclusion - -Congratulations! You've taken your first steps into the exciting world of advanced configuration in Create React App. Now you can customize your projects, add plugins, and take control of your development environment with confidence. - -Remember, the power of customization comes with great responsibility. Always experiment with caution and keep an eye on the official documentation for the latest updates and best practices. Happy coding! 🎉 \ No newline at end of file diff --git a/docs/react/advanced-usage/alternatives-to-ejecting.md b/docs/react/advanced-usage/alternatives-to-ejecting.md deleted file mode 100644 index dbc65760f..000000000 --- a/docs/react/advanced-usage/alternatives-to-ejecting.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -id: alternatives-to-ejecting -title: Alternatives to Ejecting -sidebar_label: Alternatives to Ejecting -sidebar_position: 5 -tags: [React, Create React App, Advanced Usage] -keywords: [alternatives to ejecting, create react app, react-scripts, craco, custom scripts, package.json, ejectify, custom templates, boilerplates] -description: Learn about alternatives to ejecting from Create React App and how to customize your project without ejecting. ---- - -## Introduction - -Create React App (CRA) is an awesome tool that provides a quick and easy way to set up a React project with no build configuration. However, sometimes you might find yourself needing more control over the build process or wanting to add custom configurations. The traditional way to achieve this is by ejecting from Create React App, but it can be a bit intimidating for beginners and can lead to maintenance headaches. Fear not, for there are some fantastic alternatives that will let you customize your project without the need to eject! 🚀 - -## 1. **Customize with react-scripts** - -Instead of ejecting, you can use the `react-scripts` package that comes with Create React App under the hood. It offers hidden features that you can use to tweak your project's settings without ejecting. Create a file in the root of your project called `.env`, and you can add custom environment variables like this: - -```plaintext -REACT_APP_MY_VARIABLE=hello-coders -``` - -Now you can access this variable in your code using `process.env.REACT_APP_MY_VARIABLE`. - -## 2. **CRACO - Create React App Configuration Override** - -CRACO is like magic for your Create React App projects. It stands for Create React App Configuration Override and lets you easily modify CRA's configuration without ejecting. You can add custom webpack configurations, Babel plugins, and much more, all from a single configuration file. It's like wielding a powerful wand to control your project's build process! 🧙‍♂️ - -## 3. **Custom Scripts in `package.json`** - -For simpler customizations, you can add your own scripts directly to the `package.json` file. For example, you can create a script to run a pre-build task or automate some setup steps. Just add something like this: - -```json -"scripts": { - "custom-script": "node scripts/customScript.js" -} -``` - -Then, you can run your custom script using `npm run custom-script`. - -## 4. **Ejectify - The Un-Ejecting Tool** - -Ejectify is a fun and clever tool that reverses the eject process. Instead of ejecting, you can use Ejectify to "un-eject" your Create React App project. This means you can revert to a state similar to a pre-eject status while keeping all your customizations intact! It's like traveling back in time to undo a decision without any regrets! ⏰ - -## 5. **Custom Templates and Boilerplates** - -If you have specific project requirements, you can create your own custom templates or boilerplates with all the necessary configurations pre-set. Tools like `degit` allow you to easily scaffold a new project based on your custom template, saving you time and effort. It's like having your own personalized React project starter kit! 🎁 - -## Conclusion - -As you can see, there's no need to fear the eject button anymore! With these amazing alternatives, you can confidently customize your Create React App projects without the complexity and drawbacks of ejecting. So go ahead, unleash your creativity, and build incredible React applications while keeping the magic of Create React App alive! Happy coding! 😄🚀 diff --git a/docs/react/advanced-usage/can-i-use-decorators.md b/docs/react/advanced-usage/can-i-use-decorators.md deleted file mode 100644 index 06538237d..000000000 --- a/docs/react/advanced-usage/can-i-use-decorators.md +++ /dev/null @@ -1,151 +0,0 @@ ---- -id: can-i-use-decorators -title: The Power of Decorators in CRA -sidebar_label: Use Decorators -sidebar_position: 2 -tags: [decorators, create react app, decorators in create react app, decorators in react, decorators in javascript, decorators in typescript] -keywords: [decorators, create react app, decorators in create react app, decorators in react, decorators in javascript, decorators in typescript] -description: Learn how to use decorators in Create React App to enhance and extend the functionality of your components. ---- - - -## Introduction to Decorators - -Decorators are an amazing feature in JavaScript that allows us to enhance and extend the functionality of classes and their properties. They are essentially special functions that wrap around components and add magic to our code. Create React App (CRA) supports decorators out of the box, making it super easy for us to level up our React components! In this guide, we'll delve into decorators, how to set up CRA for using them, and explore some cool examples. - -## Understanding Decorators - -In simple terms, decorators are like cool stickers that you put on your React components to make them extra special. They start with the `@` symbol, and you can think of them as powerful modifiers that can change the behavior of classes, methods, or properties. - -## Setting Up CRA for Decorators - -Before we can start using decorators in our CRA project, we need to set up the right environment. Don't worry; it's a breeze! Here's what you need to do: - -1. First, let's create your CRA project: - - ```bash - npx create-react-app my-app - cd my-app - ``` - -2. Now, let's install the magical `babel-plugin-transform-decorators-legacy` package: - - ```bash - npm install babel-plugin-transform-decorators-legacy --save-dev - ``` - -3. Finally, let's configure Babel to recognize decorators by adding the plugin in your `package.json` file: - - ```json title="package.json" - { - "name": "my-app", - "version": "0.1.0", - "babel": { - "plugins": [ - "babel-plugin-transform-decorators-legacy" - ] - } - } - ``` - -## Using Decorators in CRA - -Now comes the fun part! Let's see how we can use decorators to make our components shine: - -### Class Decorators - -Imagine class decorators as superhero capes you put on your entire component class. They can change the class's behavior or even add cool superpowers! Check this out: - -```jsx title="MyComponent.jsx" -import React from 'react'; - -function withHoverStyle(WrappedComponent) { - return class extends React.Component { - state = { isHovered: false }; - - handleMouseEnter = () => this.setState({ isHovered: true }); - handleMouseLeave = () => this.setState({ isHovered: false }); - - render() { - return ( -
- -
- ); - } - }; -} - -@withHoverStyle -class MyComponent extends React.Component { - render() { - const { isHovered } = this.props; - const style = isHovered ? { backgroundColor: 'lightblue' } : {}; - - return ( -
- {/* Your component content here */} -
- ); - } -} -``` - -In this example, the `withHoverStyle` decorator adds a nice hover effect to our component, all without modifying the original component code! - -### Method Decorators - -Method decorators are like little wizards that cast spells on specific methods in your component. Let's create a decorator to throttle an expensive method: - -```jsx title="MyComponent.jsx" -function throttle(wait) { - return function (target, key, descriptor) { - let timeout; - - descriptor.value = function (...args) { - clearTimeout(timeout); - timeout = setTimeout(() => { - target.apply(this, args); - }, wait); - }; - - return descriptor; - }; -} - -class MyComponent extends React.Component { - @throttle(500) - handleScroll() { - // Expensive operation - } -} -``` - -Here, the `throttle` decorator makes sure that the `handleScroll` method is only called every 500 milliseconds, preventing performance bottlenecks! - -### Property Decorators - -Property decorators are like the secret agents that guard your component properties. They can enforce rules or do other behind-the-scenes stuff. Let's make a property read-only: - -```jsx title="MyComponent.jsx" -function readonly(target, key, descriptor) { - descriptor.writable = false; - return descriptor; -} - -class MyComponent extends React.Component { - @readonly - title = 'My Component'; -} -``` - -Now, the `title` property cannot be changed from outside the component, keeping your data safe and sound. - -## Conclusion - -Decorators are a superpower in Create React App, and now you know how to use them to make your components even more awesome! By leveraging class, method, and property decorators, you can add exciting features, enhance behavior, and make your codebase cleaner and more organized. - -Remember, with great power comes great responsibility. Use decorators wisely and sparingly, and you'll become a true React pro in no time! Happy coding! \ No newline at end of file diff --git a/docs/react/advanced-usage/custom-templates.md b/docs/react/advanced-usage/custom-templates.md deleted file mode 100644 index c3c0a2031..000000000 --- a/docs/react/advanced-usage/custom-templates.md +++ /dev/null @@ -1,301 +0,0 @@ ---- -id: custom-templates -title: Custom Templates -sidebar_label: Importing a Component -sidebar_position: 1 -tags: [create react app, custom templates, custom template, react project, project setup, project configuration, project dependencies, project folder structure, react app, react project setup, react project configuration, react project dependencies, react project folder structure, react project template, react project scaffolding, react project boilerplate, react project starter kit, react project setup template, react project configuration template, react project dependencies template, react project folder structure template, react project scaffolding template, react project boilerplate template, react project starter kit template, react project setup boilerplate, react project configuration boilerplate, react project dependencies boilerplate, react project folder structure boilerplate, react project scaffolding boilerplate, react project starter kit boilerplate] -keywords: [create react app, custom templates, custom template, react project, project setup, project configuration, project dependencies, project folder structure, react app, react project setup, react project configuration, react project dependencies, react project folder structure, react project template, react project scaffolding, react project boilerplate, react project starter kit, react project setup template, react project configuration template, react project dependencies template, react project folder structure template, react project scaffolding template, react project boilerplate template, react project starter kit template, react project setup boilerplate, react project configuration boilerplate, react project dependencies boilerplate, react project folder structure boilerplate, react project scaffolding boilerplate, react project starter kit boilerplate] -description: Learn how to create and use custom templates in Create React App to quickly start new projects with specific configurations, dependencies, and folder structures. ---- - -## Introduction to Custom Templates - -Custom templates in Create React App (CRA) are pre-configured project setups that allow developers to scaffold new projects with specific configurations, dependencies, and folder structures. They enable you to avoid repetitive manual setup and quickly start your projects with your preferred settings. In this guide, we'll create a custom template that includes a popular UI library, sets up a state management system, and adds some custom scripts for building an engaging React app. - -:::note -This feature is available with `react-scripts@3.3.0` and higher. -::: - -Custom Templates in Create React App empower you to select a specialized project template while retaining all the benefits of Create React App's features. - -Custom Templates follow the naming convention `cra-template-[template-name]`, but you only need to provide `[template-name]` when creating a new project. - -Scoped templates are also supported using the format `@[scope-name]/cra-template` or `@[scope-name]/cra-template-[template-name]`, which can be installed via `@[scope]` and `@[scope]/[template-name]` respectively. - -To create a new project using a custom template, use the following command: - -```sh -npx create-react-app my-app --template [template-name] -``` - -## Finding Custom Templates - -Create React App ships with two default templates: - -- [`cra-template`](https://github.com/facebook/create-react-app/tree/main/packages/cra-template) -- [`cra-template-typescript`](https://github.com/facebook/create-react-app/tree/main/packages/cra-template-typescript) - -However, the community offers a wide range of great custom templates. You can find them by searching for ["cra-template-\*"](https://www.npmjs.com/search?q=cra-template-*) on npm. - -## Building a Custom Template - -If you're interested in creating your custom template, start by exploring how the default [`cra-template`](https://github.com/facebook/create-react-app/tree/main/packages/cra-template) is built. - -A custom template must adhere to the following structure: - -``` -cra-template-[template-name] - ├── README.md (for npm) - ├── template.json - ├── package.json - ├── template - | ├──README.md (for projects created from this template) - | ├──gitignore - | ├──public - | | ├──index.html - | | └── ... - | ├──src - | ├── index.js (or index.tsx) - | └── ... - └── ... -``` - -### Testing a Custom Template - -To test a custom template locally, use the `file:` prefix followed by the file path to your template source. - -```sh -npx create-react-app my-app --template file:../path/to/your/template/cra-template-[template-name] -``` - -### The `template` Folder - -The `template` folder is copied to the user's app directory when Create React App installs. During this process, the file `gitignore` is renamed to `.gitignore`. - -Feel free to add any additional files you want in this folder, but ensure you have at least the files specified above. - -### The `template.json` File - -The `template.json` file is the configuration file for your custom template. As this feature evolves, more options will be added. For now, only the `package` key is supported. - -The `package` key allows you to provide any keys/values you want to add to the new project's `package.json`. You can include dependencies and any custom scripts your template relies on. - -Below is an example `template.json` file: - -```json title="template.json" -{ - "package": { - "dependencies": { - "eslint-plugin-jsx-a11y": "^6.2.3", - "serve": "^11.2.0" - }, - "scripts": { - "serve": "serve -s build", - "build-and-serve": "npm run build && npm run serve" - }, - "eslintConfig": { - "extends": ["react-app", "plugin:jsx-a11y/recommended"], - "plugins": ["jsx-a11y"] - } - } -} -``` - -Any values you add for `"dependencies"` and `"scripts"` will merge with the Create React App defaults. For other keys, the values will be used as-is, replacing any matching Create React App defaults. - -As a convenience, we automatically replace `npm run` with `yarn` in your custom `"scripts"`, as well as in your `README` when projects are initialized with yarn. - - -## Step-by-Step Guide to Creating Custom Templates in Create React App - -### Step 1: Setting Up the Initial CRA Project - -Before creating our custom template, we need to set up a basic Create React App project. If you haven't installed CRA, do it using npm (Node Package Manager): - -```bash -npm install -g create-react-app -``` - -Once installed, create a new React app with the following command: - -```bash -npx create-react-app my-custom-template-app -``` - -Replace `my-custom-template-app` with your preferred project name. - -### Step 2: Customize Your CRA Project - -In the newly created `my-custom-template-app` directory, you'll find the basic CRA project structure. We'll now add some customizations to our template. - -#### Example Customization 1: Adding a UI Library - -For our example, let's use the popular UI library `Material-UI`. Install it using npm: - -```bash -npm install @mui/material @emotion/react @emotion/styled -``` - -Next, create a new file `CustomButton.js` in the `src` folder with the following code: - -```jsx title="CustomButton.js" -// CustomButton.js -import React from 'react'; -import Button from '@mui/material/Button'; - -const CustomButton = ({ text }) => { - return ; -}; - -export default CustomButton; -``` - -In the `src/App.js` file, import and use the `CustomButton` component: - -```jsx title="App.js" -// App.js -import React from 'react'; -import CustomButton from './CustomButton'; - -function App() { - return ( -
-

Hello, Custom Template!

- -
- ); -} - -export default App; -``` - -#### Example Customization 2: Setting Up State Management (using Redux) - -For state management, we'll integrate Redux into our custom template. Install the required packages: - -```bash -npm install redux react-redux -``` - -Now, create a new folder named `store` in the `src` directory. Inside this folder, create a file `counterSlice.js` with the following code: - -```jsx title="src/store/counterSlice.js" -// src/store/counterSlice.js -import { createSlice } from '@reduxjs/toolkit'; - -const counterSlice = createSlice({ - name: 'counter', - initialState: { value: 0 }, - reducers: { - increment(state) { - state.value += 1; - }, - decrement(state) { - state.value -= 1; - }, - }, -}); - -export const { increment, decrement } = counterSlice.actions; -export default counterSlice.reducer; -``` - -In the `src/store` folder, create a file named `store.js` to set up the Redux store: - -```jsx title="src/store/store.js" -// src/store/store.js -import { configureStore } from '@reduxjs/toolkit'; -import counterReducer from './counterSlice'; - -export default configureStore({ - reducer: { - counter: counterReducer, - }, -}); -``` - -Finally, update `src/index.js` to wrap the `App` component with the Redux Provider and pass the store: - -```jsx title="src/index.js" -// src/index.js -import React from 'react'; -import ReactDOM from 'react-dom'; -import { Provider } from 'react-redux'; -import store from './store/store'; -import App from './App'; - -ReactDOM.render( - - - , - document.getElementById('root') -); -``` - -### Step 3: Create the Custom Template - -Now that we've customized our CRA project, let's turn it into a reusable template. - -**1. Template Folder Structure** - -Create a new folder named `template` in the root directory of your CRA project. Move all the files and folders (except the `node_modules` folder) from the root to this `template` folder. - -**2. Custom Template Package.json** - -In the `template` folder, create a new `package.json` file. Add the following: - -```json title="package.json" -{ - "name": "my-custom-react-template", - "version": "0.1.0", - "dependencies": { - "@mui/material": "^5.0.0", - "@emotion/react": "^11.4.1", - "@emotion/styled": "^11.3.0", - "redux": "^4.1.1", - "react-redux": "^7.2.5", - "react-scripts": "4.0.3" - } -} -``` - -Note: The dependencies listed here should match the ones used in your CRA project. Additionally, update the version numbers if needed. - -**3. README.md** - -Create a `README.md` file in the `template` folder and add documentation for your custom template. Describe the purpose of the template, its features, and any additional setup or configuration instructions. - -### Step 4: Test Your Custom Template Locally - -Before publishing your template, test it locally to ensure everything works as expected. - -**1. Link Your Custom Template** - -In the root directory of your CRA project, run the following command to create a symlink for your custom template: - -```bash -npm link -``` - -**2. Create a New Project** - -Now, create a new directory outside your custom template project and use the following command to generate a new CRA project using your custom template: - -```bash -npx create-react-app my-custom-app --template file:../path/to/my-custom-template-app/template -``` - -Replace `../path/to/my-custom-template-app/template` with the actual path to your custom template. - -**3. Start the New Project** - -Move into the newly created `my-custom-app` directory and start the app: - -```bash -cd my-custom-app -npm start -``` - -### Conclusion - -Congratulations! You've successfully created your custom template in Create React App. Now you can reuse it or share it with others, making it easier to kickstart future React projects with your preferred configurations, dependencies, and folder structures. Happy coding! \ No newline at end of file diff --git a/docs/react/advanced-usage/pre-rendering-into-static-html-files.md b/docs/react/advanced-usage/pre-rendering-into-static-html-files.md deleted file mode 100644 index 043c9dad5..000000000 --- a/docs/react/advanced-usage/pre-rendering-into-static-html-files.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -id: pre-rendering-into-static-html-files -title: Pre-Rendering into Static HTML Files -sidebar_label: Pre-Rendering Static HTML -sidebar_position: 3 -tags: [React, Pre-Rendering, Static HTML, SEO, Performance] -keywords: [pre-rendering, static html, react pre-rendering, react static html, pre-rendering in react, static html in react, react performance, react seo] -description: Learn how to pre-render your React application into static HTML files to improve performance and SEO. ---- - -If you're hosting your React application using a static hosting provider, you have a fantastic opportunity to enhance its performance and SEO by pre-rendering it into static HTML files. Pre-rendering involves generating HTML pages for each route or link in your application, making them readily available to users even before the JavaScript bundle loads. This seamless process not only improves loading times but also boosts your website's visibility on search engines. - -## What is Pre-Rendering and Why Use It? - -Pre-rendering, also known as "snapshotting," is a technique that produces static HTML versions of your dynamic React app during the build process. This means that instead of waiting for the JavaScript to load and render the content, users receive the pre-rendered HTML instantly. It greatly improves the initial loading speed, which is crucial for providing a smooth and delightful user experience. - -### Benefits of Pre-Rendering: - -1. **Faster Initial Page Load**: Users see the core content of each page even before the JavaScript bundle finishes downloading, resulting in quicker load times and reduced bounce rates. - -2. **Improved SEO**: Search engines can easily crawl and index static HTML pages, which enhances your website's visibility and ranking in search results. - -3. **Server Load Reduction**: Pre-rendering shifts the burden of generating and caching routes from the server to the build process, optimizing server performance. - -## How to Pre-Render with `react-snapshot` or `react-snap` - -Two popular libraries, `react-snapshot` and `react-snap`, can help you achieve pre-rendering in your React application: - -1. **react-snapshot** (Link: [npm](https://www.npmjs.com/package/react-snapshot)) - - This library allows you to pre-render your app into static HTML pages for each route. The pages become active or "hydrated" once the JavaScript bundle loads. - -2. **react-snap** (Link: [npm](https://www.npmjs.com/package/react-snap)) - - Similar to `react-snapshot`, `react-snap` also generates static HTML pages for each route or relative link in your application. - -## Setting Up Pre-Rendering - -To get started with pre-rendering using either of these libraries, follow these general steps: - -1. **Create a React App**: - - If you haven't already, create a new React app using Create React App or your preferred method. - -2. **Install the Chosen Library**: - - For `react-snapshot`, use the following command: - - ```bash - npm install react-snapshot - ``` - - For `react-snap`, use: - - ```bash - npm install react-snap - ``` - -3. **Configure the Build Scripts**: - - Open your project's `package.json` file and modify the scripts section to include the pre-rendering library's command. For example: - - ```json - "scripts": { - "prebuild": "react-snapshot", // or "react-snap" for react-snap - "build": "react-scripts build" - } - ``` - -4. **Pre-Render Your App**: - - Run the following command to generate static HTML pages: - - ```bash - npm run build - ``` - -5. **Test Your Pre-Rendered App**: - - After the build process completes, you can serve your pre-rendered app locally to test it: - - ```bash - npx serve -s build - ``` - - Your pre-rendered app should now be accessible at `http://localhost:5000`. - -## Conclusion - -Pre-rendering your React app into static HTML files is a game-changer in terms of performance and SEO. By serving pre-rendered content to users, you significantly improve the initial loading speed, leading to higher user satisfaction and engagement. Moreover, search engines will have an easier time indexing your pages, potentially boosting your website's visibility. - -So go ahead, give pre-rendering a try, and experience the remarkable benefits it brings to your React applications! \ No newline at end of file diff --git a/docs/react/assets/Frontend-Roadmap.pdf b/docs/react/assets/Frontend-Roadmap.pdf deleted file mode 100644 index 7c40f8acf..000000000 Binary files a/docs/react/assets/Frontend-Roadmap.pdf and /dev/null differ diff --git a/docs/react/assets/ReactJS-Guide.pdf b/docs/react/assets/ReactJS-Guide.pdf deleted file mode 100644 index 988611d76..000000000 Binary files a/docs/react/assets/ReactJS-Guide.pdf and /dev/null differ diff --git a/docs/react/assets/audio.mp3 b/docs/react/assets/audio.mp3 deleted file mode 100644 index 27cc384fd..000000000 Binary files a/docs/react/assets/audio.mp3 and /dev/null differ diff --git a/docs/react/back-end-integration/DataFetcher.jsx b/docs/react/back-end-integration/DataFetcher.jsx deleted file mode 100644 index 8e7b5360d..000000000 --- a/docs/react/back-end-integration/DataFetcher.jsx +++ /dev/null @@ -1,32 +0,0 @@ -import { useEffect, useState } from 'react'; -import axios from 'axios'; - -const DataFetcher = () => { - const [data, setData] = useState([]); - - useEffect(() => { - const fetchData = async () => { - try { - const response = await axios.get('https://api.github.com/users/Ajay-Dhangar'); // Replace with your API endpoint - setData(response.data); - } catch (error) { - console.error('Error fetching data:', error); - } - }; - - fetchData(); - }, []); - - return ( -
-

Fetched Data

- -
- ); -}; - -export default DataFetcher; \ No newline at end of file diff --git a/docs/react/back-end-integration/FetchDataComponent.jsx b/docs/react/back-end-integration/FetchDataComponent.jsx deleted file mode 100644 index 371e6a2e1..000000000 --- a/docs/react/back-end-integration/FetchDataComponent.jsx +++ /dev/null @@ -1,38 +0,0 @@ -import { useState, useEffect } from 'react'; - -function FetchDataComponent() { - const [userData, setUserData] = useState(null); - const [error, setError] = useState(null); - - useEffect(() => { - async function fetchData() { - try { - const response = await fetch('https://api.github.com/users/Ajay-Dhangar'); - if (!response.ok) { - throw new Error('Failed to fetch data'); - } - const data = await response.json(); - setUserData(data); - } catch (error) { - setError(error); - } - } - - fetchData(); - }, []); - - return ( -
- {error &&

Error fetching data: {error.message}

} - {userData && ( -
-

Username: {userData.login}

-

Name: {userData.name}

-

Followers: {userData.followers}

-
- )} -
- ); -} - -export default FetchDataComponent; \ No newline at end of file diff --git a/docs/react/back-end-integration/_category_.json b/docs/react/back-end-integration/_category_.json deleted file mode 100644 index 4a7b67280..000000000 --- a/docs/react/back-end-integration/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Back End Integration", - "position": 8, - "link": { - "type": "generated-index", - "description": "5 minutes to learn the most important RoadMap for React Mastery." - } - } \ No newline at end of file diff --git a/docs/react/back-end-integration/fetching-data-with-ajax-requests.md b/docs/react/back-end-integration/fetching-data-with-ajax-requests.md deleted file mode 100644 index b6affc280..000000000 --- a/docs/react/back-end-integration/fetching-data-with-ajax-requests.md +++ /dev/null @@ -1,189 +0,0 @@ ---- -id: fetching-data-with-ajax-requests -title: Fetching Data with AJAX Requests in React -sidebar_label: Fetching Data -sidebar_position: 2 -tags: [React, AJAX, Data Fetching, API, Asynchronous] -keywords: [fetching data in react, ajax requests in react, data fetching in react, react ajax, react fetch, react data fetching, react api] -description: "Learn how to fetch data with AJAX requests in a React application using the `fetch()` API and the `axios` library." ---- - -import '../css/style.css'; - -In modern web development, retrieving data from a server and displaying it on a web page is a common task. To achieve this in React, we use AJAX (Asynchronous JavaScript and XML) requests. AJAX allows us to fetch data from a server without needing to reload the entire page. - - -## Prerequisites - -Before we begin, make sure you have the following: - -1. Basic knowledge of HTML, CSS, and JavaScript. -2. Node.js and npm (Node Package Manager) installed on your machine. -3. A code editor of your choice, such as Visual Studio Code or Sublime Text. - - -## Introduction to Fetching Data in React - -When building React applications, data fetching is a common requirement to interact with APIs and display dynamic content on web pages. While React doesn't enforce a specific data fetching approach, developers often use libraries like [axios](https://github.com/axios/axios) or utilize the native [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provided by modern browsers. - -In this guide, we'll explore how to fetch data with AJAX requests in React, and we'll focus on using the `fetch()` API as it's built into browsers, making it readily accessible. - -## Understanding the `fetch()` API - -The `fetch()` function is a powerful tool for making AJAX requests in modern web applications. It takes a URL as an input and returns a `Promise` that resolves to a `Response` object. If the request is successful, the `Response` object contains the data returned by the server. - -Here's a basic example of how the `fetch()` API works: - -```js -fetch('https://api.github.com/users/Ajay-Dhangar') - .then((response) => response.json()) - .then((data) => { - // Process the data here - console.log(data); - }) - .catch((error) => { - console.error('Error fetching data:', error); - }); -``` - -In this example, we use the `fetch()` function to make a GET request to the URL `https://api.github.com/users/Ajay-Dhangar`. We then use the `then()` method to handle the response. The `response.json()` method reads the response data and parses it as JSON. Finally, we handle the parsed data or catch any errors that occurred during the request. - -## Using `async / await` for a Cleaner Code - -While chaining `.then()` methods works well, it can lead to callback hell when dealing with multiple requests. To make the code cleaner and more readable, you can use the `async / await` syntax with `try / catch` blocks: - -```js -async function fetchData() { - try { - const response = await fetch('https://api.github.com/users/Ajay-Dhangar'); - const data = await response.json(); - // Process the data here - console.log(data); - } catch (error) { - console.error('Error fetching data:', error); - } -} - -// Call the fetchData function -fetchData(); -``` - -Using `async / await`, we can write asynchronous code in a more synchronous style, making it easier to understand, especially for beginners. - -## Compatibility Considerations - -Before solely relying on the `fetch()` API, ensure it's supported in your target audience's browsers. Older browsers like Internet Explorer require a [polyfill](https://github.com/facebook/create-react-app/blob/main/packages/react-app-polyfill/README.md) to use the `fetch()` API. - -## React and AJAX Data Fetching - -In a React application, you can use the `fetch()` API within components or custom hooks to fetch data from APIs. It's common to use the `useState` and `useEffect` hooks to manage the data state and trigger the data fetching process when the component mounts or when specific dependencies change. - -To learn more about integrating AJAX requests with React components and handling data effectively, refer to the [FAQ entry on the React website](https://reactjs.org/docs/faq-ajax.html). - -Remember, AJAX requests may take time to complete, so it's essential to provide proper loading indicators and error handling to create a smooth user experience. - - -## For Example: -In this guide, we'll walk you through the process of making AJAX requests in a React application using the popular tool "Create React App." - -### Step 1: Set Up a New React Project - -If you don't have a React project yet, you can create one using Create React App. Open your terminal and run the following command: - -```bash -npx create-react-app my-ajax-app -cd my-ajax-app -``` - -This will create a new React project called "my-ajax-app" and navigate you into its directory. - -### Step 2: Install Axios - -To make AJAX requests, we'll use Axios, a popular JavaScript library that simplifies the process of sending HTTP requests. In your terminal, run the following command to install Axios: - -```bash -npm install axios -``` - -### Step 3: Create a Component for Fetching Data - -Now, let's create a new component that will handle the AJAX request. In the "src" folder of your project, create a new file called "DataFetcher.js." Open the file and add the following code: - -```jsx title="DataFetcher.js" -import React, { useEffect, useState } from 'react'; -import axios from 'axios'; - -const DataFetcher = () => { - const [data, setData] = useState([]); - - useEffect(() => { - const fetchData = async () => { - try { - const response = await axios.get('https://api.github.com/users/Ajay-Dhangar'); // Replace with your API endpoint - setData(response.data); - } catch (error) { - console.error('Error fetching data:', error); - } - }; - - fetchData(); - }, []); - - return ( -
-

Fetched Data

- -
- ); -}; - -export default DataFetcher; -``` - -In this component, we use the `useEffect` hook to fetch data from the API when the component mounts. We store the fetched data in the `data` state variable using the `useState` hook. - -### Step 4: Using the DataFetcher Component - -Now that we have our `DataFetcher` component, we can use it in our main application. Open the "src/App.js" file and replace its content with the following: - -```jsx -import React from 'react'; -import DataFetcher from './DataFetcher'; - -function App() { - return ( -
-

My Awesome App

- -
- ); -} - -export default App; -``` - -Here, we import and render the `DataFetcher` component within the `App` component. - -### Step 5: Start the Development Server - -Finally, start the development server to see your app in action. Run the following command in your terminal: - -```bash -npm start -``` - -Your app will open in a new browser tab at "http://localhost:3000," showing the fetched data from the API. - -Congratulations! You've successfully implemented AJAX requests in your React app using Axios. - -## Conclusion - -Fetching data with AJAX requests is an integral part of building dynamic and interactive React applications. By using the `fetch()` API or libraries like axios, you can easily communicate with APIs and display data on your web pages. Additionally, leveraging `async / await` can improve the readability of your code and help manage multiple asynchronous requests more efficiently. - -Always keep compatibility in mind when using modern features like the `fetch()` API, and consider using polyfills for older browsers. With the knowledge of data fetching in React, you're equipped to create responsive and data-driven web applications. - -Happy coding and exploring the possibilities of data integration in your React journey! diff --git a/docs/react/back-end-integration/integrating-with-an-api-backend.md b/docs/react/back-end-integration/integrating-with-an-api-backend.md deleted file mode 100644 index 7532445ee..000000000 --- a/docs/react/back-end-integration/integrating-with-an-api-backend.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -id: integrating-with-an-api-backend -title: Integrating with an API Backend -sidebar_label: Integrating with an API -sidebar_position: 3 -tags: [React, API, Backend, Integration] -keywords: [react, api, backend, integration, axios, fetch, http, request, post, get, put, delete, data, communication, server, client, frontend, backend, fullstack, web development, javascript, node.js, express, rest, json, asynchronous, promise, async, await, state, useEffect, useState, form, submit, create, update, delete, fetch, send, receive, response, error, axios, library, package, npm, install, tool, postman, testing, endpoint, list, data, new, component, app, file, code, example, tutorial, guide, how-to, learn, step-by-step, beginner, basics, introduction, overview, explanation, example, code, source, snippet, tutorial, guide, learn, how-to, steps, react, javascript, web development, frontend, backend, fullstack, integration, api, axios, fetch, http, request, post, get, put, delete, data, communication, server, client, frontend, backend, fullstack, web development, javascript, node.js, express, rest, json, asynchronous, promise, async, await, state, useEffect, useState, form, submit, create, update, delete, fetch, send, receive, response, error, axios, library, package, npm, install, tool, postman, testing, endpoint, list, data, new, component, app, file, code, example, tutorial, guide, how-to, learn, step-by-step, beginner, basics, introduction, overview, explanation, example, code, source, snippet, tutorial, guide, learn, how-to, steps] -description: "Learn how to integrate a React app with an API backend, enabling it to fetch and send data seamlessly." ---- - - -# Integrating a React App with an API Backend - -Welcome to CodeMastermindHQ! In this tutorial, we will guide you through the process of integrating your React app with an API backend. By the end of this guide, you'll have a solid understanding of how to connect your frontend and backend, enabling your app to fetch and send data seamlessly. - -## Prerequisites - -Before we dive into the integration process, make sure you have the following: - -1. Basic knowledge of React and JavaScript. -2. Node.js and npm (Node Package Manager) installed on your computer. -3. A backend API (you can use an existing API or create a simple one for testing purposes). - -## Step 1: Set Up Your React App - -If you don't have a React app yet, you can create one using Create React App. Open your terminal and run the following command: - -```bash -npx create-react-app my-react-app -cd my-react-app -``` - -This will generate a new React app in a folder named `my-react-app`. Navigate into the folder using `cd my-react-app`. - -## Step 2: Install Dependencies - -Next, you need to install some additional packages that will help you perform API requests from your React app. Install the `axios` library by running the following command: - -```bash -npm install axios -``` - -Axios is a popular JavaScript library used to make HTTP requests, which will be handy when communicating with your backend API. - -## Step 3: Define Your API Backend - -Before we integrate our React app, ensure your backend API is up and running. Your backend should have a set of endpoints that the frontend can communicate with. For demonstration purposes, let's assume you have the following endpoints: - -- `GET /api/posts`: Retrieves a list of posts from the backend. -- `POST /api/posts`: Creates a new post on the backend. - -You can use a tool like Postman to test your backend API and verify that these endpoints are working as expected. - -## Step 4: Making API Requests - -Now, it's time to integrate your React app with the backend API. Open the file `src/App.js` in your React project, which is the main component of your app. - -### Fetching Data from the Backend - -To fetch data from the backend API, you can use the `axios` library we installed earlier. In your `App.js` file, add the following code to fetch a list of posts: - -```javascript title="App.js" -import React, { useState, useEffect } from 'react'; -import axios from 'axios'; - -const App = () => { - const [posts, setPosts] = useState([]); - - useEffect(() => { - axios.get('/api/posts') - .then(response => { - setPosts(response.data); - }) - .catch(error => { - console.error('Error fetching data:', error); - }); - }, []); - - return ( -
-

My React App

- -
- ); -}; - -export default App; -``` - -In this code, we use the `useState` and `useEffect` hooks from React to manage the state of the `posts` array. The `useEffect` hook makes an HTTP GET request to `/api/posts` when the component mounts. The response data is then used to update the `posts` state, and the list of posts is displayed in the app. - -### Sending Data to the Backend - -To send data to the backend API, such as creating a new post, you can add a form in your `App.js` file: - -```javascript title="App.js" -// ... (above code) - -const App = () => { - // ... (existing code) - - const handleSubmit = (event) => { - event.preventDefault(); - - const newPost = { - title: event.target.title.value, - body: event.target.body.value, - }; - - axios.post('/api/posts', newPost) - .then(response => { - // If successful, update the state with the new post - setPosts([...posts, response.data]); - }) - .catch(error => { - console.error('Error creating post:', error); - }); - - // Clear the form fields after submitting - event.target.reset(); - }; - - return ( -
-

My React App

-
- - -``` - -In React, a `