NW.js and Webpack: A match made in heaven
lessonDuration 4m 51sFree
Let's add some module loading to our NW.js. Webpack and dependency management FTW!
Browse
Find courses, lessons, articles, talks, and podcasts.
67 results for "webpack"
Showing 25–48 · Page 2 of 3
lessonDuration 4m 51sFree
Let's add some module loading to our NW.js. Webpack and dependency management FTW!
lessonDuration 4m 4sFree
An introduction on unit testing a ReactJS component using Webpack and Jasmine. Learn how to use Webpack to package and import dependencies plus take advantage of the babel-loader to write a simple Jasmine spec using the latest ES6 syntax.
course
When setting up a modern JavaScript app, we find ourselves trudging through the land of infinite configuration. Poi offers us an option of zero-configuration by providing sane defaults and hiding them away until you need to tweak a change to suit your needs.
lessonDuration 51sFree
If you try to use CSS Modules in TypeScript the same way you would use them in JavaScript, with webpack’s css-loader, you’ll see an error: ”TS2307: Cannot find module './styles.css'”. [typings-for-css-modules-loader](https://github.com/Jimdo/typings-for-css-modules-loader) is a drop-in replacement for css-loader that works with TypeScript and generates typings for CSS on the fly. You’ll need to install dependencies first: ``` npm install --save-dev css-loader typings-for-css-modules-loader ```
lessonDuration 5m 44s
In this lesson we will create a ‘webpack.config.js’ file from scratch. Along the way we’ll learn about the entry point, how to specify output, how to configure loaders, the Preact-specific parts of the Babel configuration, and finally how to use the ‘webpack-dev-server’ via a script in the ‘package.json’ file
case-study
Tomasz's journey with egghead began as a learner. When he had to quickly learn about React and Webpack for a new job opportunity in 2016.
article
## Introduction In this tutorial, we will be building a Task Manager App which has CRUD operation. The CRUD will involve creating, reading, updating, and deleting tasks. There will also be an additional dive in to the concept of Local Storage, which we will use to store our data. ## Prerequisites To get the most out of this tutorial, you need to be familiar with JavaScript since React is a JavaScript Framework. I wrote an article on what to learn before a JavaScript Framework like React [here](https://lexitarblog.hashnode.dev/what-to-learn-before-a-javascript-framework-in-2021). So you can check it out to understand some basic things before going into this tutorial. ## Goals - You should be able to build any CRUD App like a note-taking app after this tutorial. - You should be able to use React Hooks and understand some React concepts like states, props, and components. - You should understand the concept of Local Storage and be able to use it in other React apps. ## Final View of our App The final view of our app is displayed below, and this was achieved by styling our app according to the user interface. You can also view the [final project live](https://tasktrackerappwithreact.netlify.app/).       ## Project Installation and Set-up ## Create React App In this tutorial, we will start our project using create-react-app You don't need to install or configure tools like webpack or Babel while using Create React App because they are preconfigured and hidden so that you can focus on the code. create-react-app also sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production. On your machine you’ll need to have [Node >= 10.16 and npm >= 5.6](https://nodejs.org/en/). To create our new app, you may choose one of the following methods: - **npx -** `npx create-react-app task-manager-app` - **npm -** `npm init react-app task-manager-app` - **yarn -** `yarn create react-app task-manager-app` In this tutorial, we will use the Yarn method to create our new App, but you can use whichever method you wish. After the above operation, a new react app will be created called **task-manager-app**. The structure of the folders is shown below. ``` task-manager-app ├── README.md ├── node_modules ├── package.json ├── .gitignore ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js ├── logo.svg └── reportWebVitals.js └── setupTests.js ``` ## Project Clean-up After installing our new react app called task-manager-app then it is time to run the project on our browser and clean up unnecessary files in our app so that we can start building The Task Manager App. To run the installed React App on the same terminal, navigate to the main project folder and run the app by running the following commands in your terminal window. ``` cd task-manager-app yarn start ``` This command will start the app on **localhost:3000** and open the browser automatically. The landing page on our browser should look like this after the above operation.  Now that we have the project running already on port 3000, we can now clean up the project and write our first "Hello World". Open the **App.js** file in the **src** folder and replace all of the code with the code snippet below. Next, open the **index.css** file and clear all the default styles. ```jsx import './App.css'; function App() { return ( <h1>Hello World</h1> ); } export default App; ```  At this point, we now have our project set up and running on the browser. The next thing to do now is to start building the Task Manager App. ## Install Libraries Install all of the following libraries using npm or yarn. I will be using yarn. - `yarn add react-icons` - `yarn add sweetalert2` - `yarn add uuid` ## Bootstrap Framework The CSS framework that we will use to build this app is Bootstrap, which is very easy to use with React. In this tutorial, we will be using the CDN method to include Bootstrap in our app. Firstly you will go to the **public** folder of our app, within the public folder you'll find an **index.html** file where all our pages and components are rendered as a single page application. Then in the **index.html** file, paste the CSS CDN link in the `head` tag and the JavaScript CDN link in the `body` tag. **CSS CDN Link** ```html <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> ``` **JavaScript CDN Link** ```html <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script> ``` After pasting the two CDN Link in the necessary places, the index.html file in the public folder should look like this:  Now that our project is setup let's dive into creating our App. ## Creating App Components and Styles Components in React let you split the UI into independent, reusable pieces and think about each piece in isolation. In this section, we will create all the components that this app consists of, like the Header, AddTask, Button, Task, and Tasks Component. ## Creating Component Folder and File Names Open the `src` folder and create a new folder called `components`, then in the `components` folder, create the following five files. - `AddTask.js` - `Button.js` - `Header.js` - `Task.js` - `Tasks.js` After creating the five files and components folder, it should look like the one in the image below. ****  ## AddTask Component The `AddTask` Component will handle the form that takes in new tasks in our app. Now let's build this component and create the form. The component will consist of a form along with validation for the form. ### AddTask Form This form consists of three input tags which are used for receiving the task name, the day and time, and for submitting the details received. It also consists of some class names which are used for styling the form and making it look very nice. This form is handled by two states which help us to get the values of the form. In this case, we would be using our useState React Hook because we are using a Functional Component. ### note: **useState** It is the most important and often used hook when using Functional components. The purpose of this hook is to handle reactive data. Any data that we keep track of over time in the application is called state. When any of the data changes, React re-renders the UI. **Syntax of useState** ```jsx const [state, setState] = useState(initialState); ``` The first thing is to import this react hook(useState) into our AddTask Component. ```jsx import { useState } from 'react'; ``` After importing this hook, let's create the form in the functional component. So when we fill the form, it is stored in the **text** and **day** state, which are empty by default. ```jsx const AddTask = ({onSave}) => { const [text, setText] = useState(''); const [day, setDay] = useState(''); return ( <form className="add-form" onSubmit={onSubmit}> <div className="form-control"> <label>Task</label> <input type="text" placeholder="add task" value={text} onChange={(e) => setText(e.target.value)} /> </div> <div className="form-control"> <label>Day & Time</label> <input type="text" placeholder="add day & time" value={day} onChange{(e) => setDay(e.target.value)} /> </div> <input type="submit" className="btn btn-block" value="Save Task" /> </form> ) } export default AddTask ``` Now that we have created our form let's style it and make it look very nice. Open `src/index.css` and add our styles there. ```css .add-form { margin-bottom: 40px; } .form-control { margin: 20px 0; } .form-control label { display: block; } .form-control input { width: 100%; height: 40px; margin: 5px; padding: 3px 7px; font-size: 17px; } .form-control input:focus { outline: 0; } .btn { display: inline-block; background: #000; color: #fff; border: none; padding: 10px 20px; margin: 5px; border-radius: 5px; cursor: pointer; text-decoration: none; font-size: 15px; font-family: inherit; } .btn:focus { outline: none; color: white; } .btn-block { display: block; width: 100%; } ``` The form is now set for adding tasks. Let's now do a little validation to restrict an empty form submission and fill in the form's data. ### Form Validation Since our form is set, let's now validate it `onSubmit`, so when a user clicks on the save task button or hits enter, it should check the form data based on some conditions and alert the user if there is an error. But before we do the validation, we need to import the alert that will notify the user, which in this case it is the `sweetalert2` library that we installed. ```jsx import Swal from "sweetalert2" ``` The main logic behind the validation is that when the save task button is clicked, the `onSubmit` function will be called, and as we can see below that inside the `onSubmit` function, we used a conditional statem ent to check if the**text** and **day** state are empty and if it is empty we want to throw an alert that says "**Fill in your task and date or close the form!**". If the **text** state is empty and the **day** is available, we will also throw an alert that says **"Fill in your task!"** If the **text** state is available and the **day** is empty, we will also throw an alert that says **"Fill in your date!"** But if both the **text** and **day** state are available, then we can call the `onSave` function we passed as props from our `App` component, then the **text** and **day** state will be passed as an argument into the function. Then when our form is submitted, we want to set the two states back to an empty string **Note:** In case you don't understand the meaning of props, **Props** are arguments passed into React components, and they can be simply called properties. The main purpose of props is to pass data from one component to another. ```jsx const onSubmit = (e) => { e.preventDefault(); if (!text && !day) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Fill in your task and date or close the form!' }) } else if (!text && day) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Fill in your task!' }) } else if (text && !day) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Fill in your date!' }) } else { onSave({ text, day }); } setText(''); setDay(''); } ``` At this point of the tutorial, we have successfully created our `AddTask` Component by creating the AddTask form and validating it based on some conditions stated above. Your `AddTask` Component should look like this after following the above process: ```jsx import { useState } from 'react'; import Swal from "sweetalert2"; const AddTask = ({ onSave }) => { const [text, setText] = useState(''); const [day, setDay] = useState(''); const onSubmit = (e) => { e.preventDefault(); if (!text && !day) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Fill in your task and date or close the form!' }) } else if (!text && day) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Fill in your task!' }) } else if (text && !day) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Fill in your date!' }) } else { onSave({ text, day }); } setText(''); setDay(''); } return ( <form className="add-form" onSubmit={onSubmit}> <div className="form-control"> <label>Task</label> <input type="text" placeholder="add task" value={text} onChange={(e) => setText(e.target.value)} /> </div> <div className="form-control"> <label>Day & Time</label> <input type="text" placeholder="add day & time" value={day} onChange={(e) => setDay(e.target.value)} /> </div> <input type="submit" className="btn btn-block" value="Save Task" /> </form> ) } export default AddTask; ``` ## Button Component The Button Component is not very large, but the reason for creating it as a component is so that it can be re-used anywhere else in the app. If you check the App Header, the `Add` button, which later changes to `Close`, is the button component, and in this section, we will be creating the button. In the **Button.js** file you created in the **components** folder paste the code below. ```jsx const Button = ({ color, text, onClick }) => { return <button onClick={onClick} style={{ backgroundColor: color }} className="btn">{text}</button> } export default Button ``` In this component, three props (**color, text, onClick**) were passed into it from the `Header` Component, which we will create in the next section. ## Header Component The Header Component consists of the App Name, which is **"Task Manager App"** and the imported `Button` Component. In this component, we also have two props which are **(showForm, changeTextColor)**, and they are both used to show the form and change the text and color of the button, respectively. ```jsx import React from 'react'; import Button from './Button'; import "../index.css"; const Header = ({ showForm, changeTextAndColor }) => { return ( <header className="header"> <h2 className="app-header">Task Manager App</h2> <Button onClick={showForm} color={changeTextAndColor ? 'red' : 'green'} text= {changeTextAndColor ? 'Close' : 'Add'} /> </header> ) } export default Header; ``` The Header Component will also be styled with the CSS code below: ```css .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; } .app-header { font-family: "Josefin Sans", sans-serif; } ``` ## Task Component This Component will define the structure of our added tasks. We will build this component according to the user interface in our complete App look. In this component, we will be using two icons from the React Icons library for the edit and delete features. We will also pass three props which are **(task, onDelete, onEdit)**. The purpose of these props is to show the added, deleted, and edited tasks. ```jsx import { FaPencilAlt, FaTimes } from 'react-icons/fa'; import "../index.css" const Task = ({ task, onDelete, onEdit }) => { return ( <div> <div className="task"> <div> <p className="taskName"> <span className="textBold">Task Name:</span> {task.text} </p> <p className="taskDate"><span className="textBold">Date of Completion:</span> {task.day} </p> </div> <div> <p><FaTimes onClick={() => onDelete(task.id)} className="delIcon" /></p> <p><FaPencilAlt onClick={() => onEdit(task.id)} className="editIcon" /></p> </div> </div> </div> ) } export default Task; ``` This Component will also come out nice by styling it with the CSS below: ```css .task { background: #f4f4f4; margin: 5px; padding: 10px 20px; cursor: pointer; border-radius: 5px; display: flex; justify-content: space-between; } .textBold { font-weight: bold; } .delIcon { color: red; cursor: pointer; } .editIcon { color: blue; cursor: pointer; } ``` Then let's move to create our last Component! ## Tasks Component This Component is very short and precise. It receives the `tasks`, `onDelete` and `onEdit` props then maps through the `tasks`, and passing each task down along with the edit and delete functions to the `Task` Component we created above. ```jsx import Task from './Task'; import "../index.css" const Tasks = ({ tasks, onDelete, onEdit }) => { return ( <> { tasks.map((task) => ( <Task key={task.id} task={task} onDelete={onDelete} onEdit={onEdit} /> )) } </> ) } export default Tasks; ``` At this point, we are done with building all of the Components of our Task Manager App. Now we can now move on to adding the CRUD operations and some other minor features to our app. ## App Features The following is the main section of our tutorial. Here we will be adding the CRUD operations. ### App.js Set-up Before we start writing the functions that perform all these features, let's prepare our **App.js** file by importing all the components and libraries that are needed, and set up the display of our app. ### App.js Imports Navigate to **src/App.js**. In this file, we need three components that we created in the previous section, the `useState` and `useEffect` hooks, as well as the `uuid` and `sweetalert2` libraries. ```jsx // Components import Header from './components/Header'; import Tasks from './components/Tasks'; import AddTask from './components/AddTask'; // Hooks import { useState, useEffect } from 'react'; // Packages import { v4 as uuidv4 } from 'uuid'; import Swal from "sweetalert2"; ``` ### note: **useEffect** It allows us to implement all of the lifecycle methods from within a single function API. It is used majorly when a component renders just like "**componentDidMount**" in a Class-based component. ```jsx useEffect(() => { alert("Welcome to our App"); }, []); ``` After the imports, let's render all the components in our **App** component, but before we do that, we need to make use of the **useState** hook to reveal the AddTask Component, and check that we have more than 0 tasks. ```jsx const [tasks, setTasks] = useState([]); // Task State const [showAddTask, setShowAddTask] = useState(false); // To reveal add task form ``` An added task will be pushed into the `tasks` state array. The `showAddTask` state is `false` initially, which means the `AddTask` form will not show unless it is `true`, and to toggle it to `true`, we use the button in the `Header` Component. We also pass the function `addTask` through an `onSave` prop in the `AddTask` component. We'll write that function next. ```jsx function App() { // All States const [tasks, setTasks] = useState([]); // Task State const [showAddTask, setShowAddTask] = useState(false); // To reveal add task form return ( <> <div className="container"> {/* App Header */} <Header showForm={() => setShowAddTask(!showAddTask)} changeTextAndColor={showAddTask} /> {/* Revealing the Add Task Form */} {showAddTask && <AddTask onSave={addTask} />} {/* Displaying Tasks */} { tasks.length > 0 ? (<Tasks tasks={tasks} />) : ('No Task Found!') } </div> </> ) } export default App; ``` Our **App.js** is set. Without further ado, let's dive into the features in the order below. - Creating Tasks. - Updating Tasks. - Deleting Tasks. - Adding the Counter Feature. ### Creating Tasks We created the form component and validated it to make sure the data from the form is correct. So, we just need to write a function that gets the data using the **task** argument, and then set the **tasks** state to the form data so that the **tasks** state can be mapped through and to display the **tasks** on our page. - Gets the form data through the `task` argument - Creates a unique ID using the `uuid` library - Creates a `newTask` object with the `id` and spread `task` arg - Uses the `setTasks` functions to add the `newTask` to the end of the `task` state array - Uses the `sweetalert2` library to fire an alert when a task is created successfully ```jsx // Add Task const addTask = (task) => { const id = uuidv4(); const newTask = { id, ...task } setTasks([...tasks, newTask]); Swal.fire({ icon: 'success', title: 'Yay...', text: 'You have successfully added a new task!' }) } ``` ### Deleting Tasks Deleting is one of the core features of the CRUD operation, and in this section, we will build this feature. We need to delete items by **id**. So, if I have the `id` of the item I want to delete, I can filter the list of all items by `id` and return a list of items without the item with a matching `id`. Next thingis to create a function that carries out our delete feature, The name of our function is **deleteTask.** The id we are passing as argument in the function below is gotten from the `Task` Component we created above, and below is a code showing it: ```jsx <p><FaTimes onClick={() => onDelete(task.id)} className="delIcon" /></p> ``` So clicking the "**FaTimes**" icon fires the `deleteTask` function that was passed down through the **onDelete** props which was passed down from the **App** component down to **Tasks** then to **Task**. If a task is successfully deleted, it throws an alert saying, "**You have successfully deleted a task!"** ```jsx // Delete Task const deleteTask = (id) => { const deleteTask = tasks.filter((task) => task.id !== id); setTasks(deleteTask); Swal.fire({ icon: 'success', title: 'Oops...', text: 'You have successfully deleted a task!' }) } ``` ### Updating Tasks Like in our delete feature, we will use **id** to find our unique item and update it. We will also use a window prompt to receive new data from the user so that it can replace the previous data. In the `Task` Component, when we click on the edit icon, which was gotten from react icons, it calls the **editTask** function in the **App.js** file. So the `editTask` function was passed into this component as the `onEdit` prop. ```jsx <p><FaPencilAlt onClick={() => onEdit(task.id)} className="editIcon" /></p> ``` Below is the function that takes in the task id and prompts a user to fill new changes to the task and, before it can get updated, we need to map through our tasks id and get that particular one so that we can set that id's data to the new data we are filling. After this, the task gets updated. Bellow is the `editTask` function definition. In the function we assign the `text` and `day` variables with values from prompts. We then map through the `tasks` state array. If the `task`'s `id` matches the `id` argument, we return an object with the new data. Otherwise, we just return the task. If a task is successfully updated, it throws an alert saying **"You have successfully edited an existing task!"** ```jsx // Edit Task const editTask = (id) => { const text = prompt("Task Name"); const day = prompt("Day and Time"); const myData = tasks.map(x => { if (x.id === id) { return { ...x, text: text, day: day, id: uuidv4() } } return x; }) Swal.fire({ icon: 'success', title: 'Yay...', text: 'You have successfully edited an existing task!' }) } ``` <EmailSubscribeWidget /> ### Adding the Counter Feature. This is the easiest feature because it is just about getting the length of the **tasks** state array, so below is a code snippet that shows how to get a count of all tasks added. ```jsx {/* Task Counter */} <h3>Number of Tasks: {tasks.length}</h3> ``` ### Adding the Loading Spinner In real-world applications where you will use an API, you need to add a spinner/loader that is displayed before your data from the backend is ready to be shown to the users. In this case, we are not using an API, but for practice, let us add a spinner that loads before our main page renders. There are a lot of React spinners or loaders we can use but let's use a Bootstrap spinner to keep this app very simple but awesome. This is the [link](https://getbootstrap.com/docs/5.0/components/spinners/) to the Bootstrap Docs where you can find different Bootstrap spinners, and you are free to check out any of them. You can also check out React Spinners like those from the [react-spinners](https://www.npmjs.com/package/react-spinners) library. We would be adding our spinner to the **App.js** file because this is where all the components in our application are rendered. There are just three things to do: - Create a `loading` state using React's `useState` hook - Set our loading to false after page renders using `useEffect` hook - Put a condition in our page render to check if loading is `true` or `false`. Setup the loading state. The initial state should be `true`. ```jsx const [loading, setloading] = useState(true); // Pre-loader before page renders ``` Setting our `loading` state to `false` with `useEffect` after three and a half seconds. This behavior simulates waiting for an API call to return data to us. ```jsx useEffect(() => { setTimeout(() => { setloading(false); }, 3500); }, []) ``` Now, we can use a ternary that checks if the `loading` state is `true`, if it is our spinner should show and our page won't render yet. If it is `false` our page will render. ```jsx return ( <> { loading ? <div className="spinnerContainer"> <div className="spinner-grow text-primary" role="status"> <span className="visually-hidden">Loading...</span> </div> <div className="spinner-grow text-secondary" role="status"> <span className="visually-hidden">Loading...</span> </div> <div className="spinner-grow text-success" role="status"> <span className="visually-hidden">Loading...</span> </div> <div className="spinner-grow text-danger" role="status"> <span className="visually-hidden">Loading...</span> </div> <div className="spinner-grow text-warning" role="status"> <span className="visually-hidden">Loading...</span> </div> </div> : <div className="container"> {/* App Header that has open and App Name */} <Header showForm={() => setShowAddTask(!showAddTask)} changeTextAndColor={showAddTask} /> {/* Revealing of Add Task Form */} {showAddTask && <AddTask onSave={addTask} />} {/* Task Counter */} <h3>Number of Tasks: {tasks.length}</h3> {/* Displaying of Tasks */} { tasks.length > 0 ? (<Tasks tasks={tasks} onDelete={deleteTask} onEdit={editTask} />) : ('No Task Found!') } </div> } </> ) ``` Let’s add little styling to our spinner. Still in the index.css file, we would style the **spinnerContainer** as shown below: ```css .spinnerContainer { margin: 20% auto; max-width: 15%; } ``` ## Using Local Storage The localStorage object stores data without an expiration date. The data will not be deleted when the browser is closed. In this App, we will be using LocalStorage to store our tasks data so the user has access to them even after leaving the page in any way. In production you would use a database of some kind but we are using LocalStorage as practice. We'll be using the following `localStorage` methods: - [.setItem("key", "value")](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem) - [.getItem("key")](https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem) - [.removeItem("key")](https://developer.mozilla.org/en-US/docs/Web/API/Storage/removeItem) ### Fetching our App Data from Local Storage Before this section, we were getting our app data from the tasks state, but all our data will be empty once we reload, so in order to persist our data let's set our state with the data in `localStorage`. So once the page loads using `useEffect`, it loads the app data from `localStorage`. ```jsx // Fetching from Local Storage const getTasks = JSON.parse(localStorage.getItem("taskAdded")); useEffect(() => { if (getTasks == null) { setTasks([]) } else { setTasks(getTasks); } }, []) ``` ## Saving Added Tasks to LocalStorage At the end of the `addTask` function we wrote earlier, we would need to save the data the user is adding by using the above syntax of LocalStorage. So it will look like the code below. Our **key** is `taskAdded` and **value** is newTask. ```jsx localStorage.setItem("taskAdded", JSON.stringify([...tasks, newTask])); ``` Our overall addTask function after implementing LocalStorage should look like this: ```jsx const addTask = (task) => { const id = uuidv4(); const newTask = { id, ...task } setTasks([...tasks, newTask]); Swal.fire({ icon: 'success', title: 'Yay...', text: 'You have successfully added a new task!' }) localStorage.setItem("taskAdded", JSON.stringify([...tasks, newTask])); } ``` ## Updating LocalStorage for Deleted Tasks We would need to also set the result after an item is deleted to `localStorage` so that it can be current with our latest changes. So using the same **key** but now another value, let's set it to the result of the `deleteTask` function. ```jsx localStorage.setItem("taskAdded", JSON.stringify(deleteTask)); ``` Our `deleteTask` function should look like this: ```jsx // Delete Task const deleteTask = (id) => { const deleteTask = tasks.filter((task) => task.id !== id); setTasks(deleteTask); Swal.fire({ icon: 'success', title: 'Oops...', text: 'You have successfully deleted a task!' }) localStorage.setItem("taskAdded", JSON.stringify(deleteTask)); } ``` ## Updating LocalStorage for Edited Tasks We also need to set the result after an item is edited to `localStorage` so that it can be current with our latest changes. So we get our data from `localStorage`, map through it, then edit it the task with a matching `id` property. Using the same **key** but now another value, lets set the new data to `localStorage` with our `editTask` function. Our app also needs to be reloaded so that our state can carry the latest changes. ```jsx localStorage.setItem("taskAdded", JSON.stringify(myData)); window.location.reload(); ``` Our `editTask` function should look like this: ```jsx // Edit Task const editTask = (id) => { const text = prompt("Task Name"); const day = prompt("Day and Time"); let data = JSON.parse(localStorage.getItem('taskAdded')); const myData = data.map(x => { if (x.id === id) { return { ...x, text: text, day: day, id: uuidv4() } } return x; }) Swal.fire({ icon: 'success', title: 'Yay...', text: 'You have successfully edited an existing task!' }) localStorage.setItem("taskAdded", JSON.stringify(myData)); window.location.reload(); } ``` At this point, our tasks are being fetched from `localStorage`. If you edit or delete a task, it will also be updated in `localStorage`. Our final **App.js** file should look like this: ```jsx // Importing Components import Header from './components/Header'; import Tasks from './components/Tasks'; import AddTask from './components/AddTask'; // Importing React Hooks import { useState, useEffect } from 'react'; // Importing Packages import { v4 as uuidv4 } from 'uuid'; import Swal from "sweetalert2"; function App() { // All States const [loading, setloading] = useState(true); // Pre-loader before page renders const [tasks, setTasks] = useState([]); // Task State const [showAddTask, setShowAddTask] = useState(false); // To reveal add task form // Pre-loader useEffect(() => { setTimeout(() => { setloading(false); }, 3500); }, []) // Fetching from Local Storage const getTasks = JSON.parse(localStorage.getItem("taskAdded")); useEffect(() => { if (getTasks == null) { setTasks([]) } else { setTasks(getTasks); } }, []) // Add Task const addTask = (task) => { const id = uuidv4(); const newTask = { id, ...task } setTasks([...tasks, newTask]); Swal.fire({ icon: 'success', title: 'Yay...', text: 'You have successfully added a new task!' }) localStorage.setItem("taskAdded", JSON.stringify([...tasks, newTask])); } // Delete Task const deleteTask = (id) => { const deleteTask = tasks.filter((task) => task.id !== id); setTasks(deleteTask); Swal.fire({ icon: 'success', title: 'Oops...', text: 'You have successfully deleted a task!' }) localStorage.setItem("taskAdded", JSON.stringify(deleteTask)); } // Edit Task const editTask = (id) => { const text = prompt("Task Name"); const day = prompt("Day and Time"); let data = JSON.parse(localStorage.getItem('taskAdded')); const myData = data.map(x => { if (x.id === id) { return { ...x, text: text, day: day, id: uuidv4() } } return x; }) Swal.fire({ icon: 'success', title: 'Yay...', text: 'You have successfully edited an existing task!' }) localStorage.setItem("taskAdded", JSON.stringify(myData)); window.location.reload(); } return ( <> { loading ? <div className="spinnerContainer"> <div className="spinner-grow text-primary" role="status"> <span className="visually-hidden">Loading...</span> </div> <div className="spinner-grow text-secondary" role="status"> <span className="visually-hidden">Loading...</span> </div> <div className="spinner-grow text-success" role="status"> <span className="visually-hidden">Loading...</span> </div> <div className="spinner-grow text-danger" role="status"> <span className="visually-hidden">Loading...</span> </div> <div className="spinner-grow text-warning" role="status"> <span className="visually-hidden">Loading...</span> </div> </div> : <div className="container"> {/* App Header that has open and App Name */} <Header showForm={() => setShowAddTask(!showAddTask)} changeTextAndColor={showAddTask} /> {/* Revealing of Add Task Form */} {showAddTask && <AddTask onSave={addTask} />} {/* Task Counter */} <h3>Number of Tasks: {tasks.length}</h3> {/* Displaying of Tasks */} { tasks.length > 0 ? (<Tasks tasks={tasks} onDelete={deleteTask} onEdit={editTask} />) : ('No Task Found!') } </div> } </> ) } export default App; ``` ## Our Entire App Styles In our App, we use a general styling like our font-family (Josefin Sans), body styling, and a general container for our app to make it look well across desktop to mobile screens. All the styles we used above will also be there. So open your **index.css** file to paste the styles below there: ```css @import url("https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap"); * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: "Josefin Sans", sans-serif; background-image: url("./images/bg.jpg"); background-repeat: no-repeat; background-size: cover; background-position: center; background-attachment: fixed; height: 600px; } .spinnerContainer { margin: 20% auto; max-width: 15%; } .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; } .app-header { font-family: "Josefin Sans", sans-serif; } .container { max-width: 600px; margin: 30px auto; overflow: auto; min-height: 300px; padding: 30px; border-radius: 5px; background-color: #ccc; } .btn { display: inline-block; background: #000; color: #fff; border: none; padding: 10px 20px; margin: 5px; border-radius: 5px; cursor: pointer; text-decoration: none; font-size: 15px; font-family: inherit; } .btn:focus { outline: none; color: white; } .btn-block { display: block; width: 100%; } .task { background: #f4f4f4; margin: 5px auto; max-width: 100%; padding: 10px 20px; cursor: pointer; border-radius: 5px; overflow: scroll; display: flex; justify-content: space-between; } .task::-webkit-scrollbar { display: none; } .textBold { font-weight: bold; } .delIcon { color: red; cursor: pointer; } .editIcon { color: blue; cursor: pointer; } .add-form { margin-bottom: 40px; } .form-control { margin: 20px 0; } .form-control label { display: block; } .form-control input { width: 100%; height: 40px; margin: 5px; padding: 3px 7px; font-size: 17px; } .form-control input:focus { outline: 0; } @media (max-width: 768px) { .spinnerContainer { margin: 250px auto 0 auto; max-width: 30%; } } @media (max-width: 425px) { .container { max-width: 90%; } .spinnerContainer { margin: 250px auto 0 auto; max-width: 40%; } } @media (max-width: 375px) { .container { max-width: 95%; } .app-header { font-size: 20px; } .spinnerContainer { margin: 250px auto 0 auto; max-width: 45%; } } @media (max-width: 320px) { .container { max-width: 95%; } .app-header { font-size: 18px; } .spinnerContainer { margin: 250px auto 0 auto; max-width: 50%; } } ``` ## Resources Read up on some of the concepts covered in this tutorial in the links below. - [React Docs](https://reactjs.org/docs/) - [React Hooks](https://dev.to/abhisheknaiidu/10-react-hooks-explained-3ino) - [LocalStorage](https://www.w3schools.com/jsref/prop_win_localstorage.asp) - [Bootstrap Docs](https://getbootstrap.com/docs/5.0/getting-started/introduction/) ## Conclusion In this tutorial, we learned how to build a CRUD App with React and Local Storage, how to set up React with create-react-app, React Hooks, React States, and Props, and I believe that with this article, every reader should be able to build a very nice CRUD App. Here is a link to the project [repo](https://github.com/Lexitar32/Task-Tracker-App-with-React.js) for more guides and the [live project](https://tasktrackerappwithreact.netlify.app/). If you have any questions, you can always send me a message on [Twitter](https://twitter.com/TheCodeLord), and I will respond. <CourseWidget slug="develop-accessible-web-apps-with-react" /> <EmailSubscribeWidget />
article
<CourseWidget slug="craft-scalable-custom-made-interfaces-with-tailwind-css" /> <div className="prose-reset text-lg font-medium pb-8"> When you release a modern website one thing is clear...{' '} <mark>users expect dark mode</mark> out of the box. They aren't interested in your excuses. They don't care about the time it will take to implement, they just want dark mode. Now. </div> ## What you will learn about in this article. This article is going to explain in clear steps how to add TailwindCSS native dark mode to a Next.js site, including the TailwindCSS Typography plugins `prose` classes. There is an assumption that you have a working knowledge of both TailwindCSS and Next.js and a site that you'd like to implement a toggle between a `dark` and a `light` theme. To do this, you will use: - Next.js: A React "meta-framework" - TailwindCSS: A utility-class system for styling web applications - TailwindCSS Typography: A plugin that provides a set of `prose` classes that provide consistently nice looking typographic defaults (useful for Markdown files, for instance) - next-themes: React Hooks based utility library for Next.js that let's you switch themes in your application. ## Motivation for dark mode With a recent relaunch of egghead.io there were daily requests for a "dark mode" for the website. In the past our site had had a default singular dark theme, meaning a theme where the background is dark, and the text is light. The new site presented a solid white–incredibly bright–theme that wasn't very pleasant for many users viewing experience. Bright themes are particularly aggravating when you are working in a dark room, and some users have vision troubles that are exacerbated by light or dark themes. This means that the ability to choose between one or the other is often critical for some users' ability to use the site at all. ## Getting Started If you don't have a Next.js + TailwindCSS site to work from, [here's a github branch from my Next.js Tailwind Starter](https://github.com/joelhooks/next-typescript-tailwind-mdx-starter/tree/1-pre-dark-mode) that is "pre-dark mode" that you can use. From this point we need to update some configuration files. ### The Tailwind Config `tailwind.config.js` is in the root directory of the project and provides TailwindCSS the information it needs to correctly run in your environment. The TailwindCSS team has done a great job giving us sensible defaults, but almost every project will have specific needs and requirements that require custom configuration. ```javascript module.exports = { purge: ['./src/**/*.tsx'], theme: { typography: (theme) => ({}), extend: {}, }, variants: {}, plugins: [require('@tailwindcss/typography')], } ``` This config is almost as basic as it can be. Since you are using the TailwindCSS Typography plugin, this config let's TailwindCSS know that you want to use it. The config also has a `purge` property that provides an array o [globs](https://www.man7.org/linux/man-pages/man7/glob.7.html) letting TailwindCSS know which files it should analyze for purging extra classes not used in your application. If we didn't configure purging, the result would be _every single class TailwindCSS has to offer_ being shipped with our application. That might not be the end of the world, but it is a **lot** of extra bundle size that your users will never actually need. So we purge. After the purge configuration the see the `theme`, `variants`, and `plugins`. Right now these sections are sparse, but that's about to change. ## Enabling Dark Mode in TailwindCSS Enabling dark mode in TailwindCSS is effectively the flip of a switch: ```javascript module.exports = { darkMode: 'class', purge: ['./src/**/*.tsx'], theme: { typography: (theme) => ({}), extend: {}, }, variants: {}, plugins: [require('@tailwindcss/typography')], } ``` By adding `darkmode: 'class'` to the config, you've instructed TailwindCSS to include all of the CSS utility classes for dark mode. This enables a `dark` variant that you can now add as classes to your React elements like `className="bg-white dark:bg-gray-900"` and the correct class will be provided when `dark` is active on your `html` element. To test out dark mode in the Next.js app, you'll need to make a couple of changes to the `/src/_document.tsx` source file that is used to provide custom document structure to the Next.js application. ```jsx <Html className="dark"> <body className="dark:bg-gray-800"> <Main /> <NextScript /> </body> </Html> ``` First we add the `dark` class to the `Html` element. This enables the dark mode for the entire application. Then we add `dark:bg-gray-800` to the `body` element to provide a dark background for the Next'js application when it is in dark mode. `yarn dev` will run the application, and you should see a dark background. Delete `dark` from the `Html` elements `className` and your app should refresh with a default white background. We've achieved dark mode! 🌑 Obviously your users aren't going to change source code to enabled toggling, so the next step is to add a button that will toggle the dark mode on and off. ## Creating a theme with next-themes and React Hooks Technically your app is going to have two themes: `light` and `dark` Potentially your app could have many themes up to and including [hot dog stand](https://blog.codinghorror.com/a-tribute-to-the-windows-31-hot-dog-stand-color-scheme/). That's amazing if you want to provide your users with that level of flexibility! lol There are several relatively complicated ways you might approach the problem of toggling themes. As with many things in the React.js and Next.js world, somebody else has already solved the problem very well, and for this the community favorite is [next-themes](https://github.com/pacocoursey/next-themes) which promises (and subsequently delivers) a "perfect dark mode in two lines of code". Yes please. `yarn add next-themes` Open `/src/_app.tsx` ```jsx function MyApp({Component, pageProps}: AppProps) { return ( <> <DefaultSeo {...SEO} /> <Component {...pageProps} /> </> ) } ``` Now, in `/src/_app.js` import the `ThemeProvider` and wrap your application `Component` with it: ```jsx import {ThemeProvider} from 'next-themes' function MyApp({Component, pageProps}: AppProps) { return ( <> <DefaultSeo {...SEO} /> <ThemeProvider> <Component {...pageProps} /> </ThemeProvider> </> ) } ``` So far, nothing has really changed in the app. Since `dark` is hard-coded in your `_app.tsx` and there is no mechanism to toggle the mode, your application is stuck in dark mode. Go ahead and delete the `className` from the `Html` element: ```jsx <Html> <body className="dark:bg-gray-800"> <Main /> <NextScript /> </body> </Html> ``` Your application will reload, and will once again have the default white background that got us into this situation in the first place. <EmailSubscribeWidget /> ### Toggling between light and dark modes with just a click Open `/src/pages/index.tsx`: ```jsx export default function Home() { return ( <div> <h1 className="text-3xl text-pink-500" css={{backgroundColor: 'teal'}}> Welcome to Your App </h1> </div> ) } ``` This is relatively simple React page component that is located at the root of the site. It defines a `div` as a container and an `h1` element with a bit of welcome text and some questionably stylish classes applied. To make the toggle work, we need to import a hook from `next-themes`, manage a little piece of state, and wire it all together in a button. First, import the `useTheme` hook: ```jsx import {useTheme} from 'next-themes' export default function Home() { return ( <div> <h1 className="text-3xl text-pink-500" css={{backgroundColor: 'teal'}}> Welcome to Your App </h1> </div> ) } ``` Now call the `useTheme` hook to gain access to `theme` and `setTheme`. ```jsx import {useTheme} from 'next-themes' export default function Home() { const {theme, setTheme} = useTheme() return ( <div> <h1 className="text-3xl text-pink-500" css={{backgroundColor: 'teal'}}> Welcome to Your App </h1> </div> ) } ``` Now, add a `button` element with an `onClick` handler to use as a toggle: ```jsx import {useTheme} from 'next-themes' export default function Home() { const {theme, setTheme} = useTheme() return ( <div> <h1 className="text-3xl text-pink-500" css={{backgroundColor: 'teal'}}> Welcome to Your App </h1> <button onClick={}>toggle</button> </div> ) } ``` To toggle, we want to check and see what the current theme is, and set the appropriate theme based on that: ```jsx import {useTheme} from 'next-themes' export default function Home() { const {theme, setTheme} = useTheme() return ( <div> <h1 className="text-3xl text-pink-500" css={{backgroundColor: 'teal'}}> Welcome to Your App </h1> <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}> toggle </button> </div> ) } ``` A couple of things to note are: 1. The button is completely unstyled and doesn't really look like a button 2. clicking it does absolutely nothing 😭 The first issue just means you need to use tailwind to make the button look awesome, but the second issue is more concerning and you need to address that to get this toggle working at all. It's a multi-faceted problem resulting from how we've configured dark mode. In the `tailwind.config.js` you set `darkMode` with the `class` option. This configuration property also has a `media` option that uses the `prefers-color-scheme` media of modern browsers and operating systems to look at how the user has configured their system. The `class` option, however, means we can select and toggle the mode. In fact, you could delete the `button`, set the `darkMode` config to `media` and call it a day. For many use cases the `class` config is the most flexible and is preferred. In `/src/_app.js` you need to tell the `ThemeProvider` to use the class attribute: ```jsx <ThemeProvider attribute="class"> <Component {...pageProps} /> </ThemeProvider> ``` Let your app compile, refresh the page, and start toggling. Back and forth. Dazzling. A **fully configured dark mode powered by Tailwind CSS in a Next.js app**. The future is now. ## Solving some problems with our TailwindCSS config and dark mode This is great. It works! There are still a couple of problems to solve: 1. Build times are slooooooow (on large projects they can also completely run out of memory) 2. If you visit `/hi` - an mdx file rendered and presented with TailwindCSS Typography `prose` class, you notice that the text is black. ### Slow builds with TailwindCSS Dark Mode and Next.js This is a known problem that is at the core a webpack issue and both the Next.js team and the TailwindCSS team are aware of it. Basically, TailwindCSS + Dark Mode is a **massive** CSS file, and webpack hates building source maps for massive CSS files. <Callout className="p-4"> 👋 If you know how to solve this please hit me up on{' '} <a href="https://twitter.com/jhooks">Twitter</a> </Callout> For our application this is a huge hassle and requires that we run the development environment with additional memory allocated to node: ```bash NODE_OPTIONS=--max-old-space-size=4048 yarn dev ``` Ultimately it's a small price to pay for dark mode, and will eventually be fixed upstream. It was also alleviated a bit for us by turning on purging for the dev environment in `tailwind.config.css` ```js module.exports = { darkMode: 'class', purge: { enabled: true, content: ['./src/**/*.tsx'], }, theme: { typography: (theme) => ({}), extend: {}, }, variants: {}, plugins: [require('@tailwindcss/typography')], } ``` These options require `purge` to be an object instead of an array. We set `enabled: true` and `content: ['./src/**/*.tsx']` which is the same array as we had previously set `purge` to. Purging CSS means that TailwindCSS tries it best to analyze the source that you've pointed to in `content` and not remove any CSS classes that you've used. You can test it now by running the following commands: ```bash yarn build yarn start ``` ### Controlling the Purge If all is well, your app should function as expected. If toggling dark mode doesn't work or appear to do anything, it could mean that the `dark` CSS class variants have been stripped from your application because the `dark` class isn't assigned to a `className` by default. In this example, that doesn't appear to be happened, but if you encounter this in your application where it works in development, but not in production you might need to add a `safelist` property to your `tailwind.config.js` purge options: ```js module.exports = { darkMode: 'class', purge: { enabled: true, content: ['./src/**/*.tsx'], options: { safelist: ['dark'], //specific classes }, }, theme: { typography: (theme) => ({}), extend: {}, }, variants: {}, plugins: [require('@tailwindcss/typography')], } ``` The `safelist` allows you to specify classes that TailwindCSS will always keep around for you and not purge. At the time of this writing the only documentation for this is [buried in some Github issue comments](https://github.com/tailwindlabs/tailwindcss/discussions/2793#discussioncomment-142172). ## Dark Mode for TailwindCSS Typography Prose Classes By default TailwindCSS Typography doesn't support dark mode. Prose classes are also notoriously challenging to customize. You can't just set a `className` instead you need to override defaults in your `tailwind.config.js`: ```js module.exports = { //... theme: { extend: { typography: (theme) => ({ dark: { css: { color: 'white', }, }, }), }, }, //... } ``` In the `theme` section of the config you a `typography` property under `extend` which allows us to **extend** the `@tailwindcss/typography` plugin. The configuration property takes a function that passes in the `theme` and returns an object that extends the theme for that plugin. It makes me a little dizzy to think about, but the extension we return adds a `dark` property with a `css` property that sets `color: 'white'` Now, in `/src/layouts/index.tsx` on line 28 you'll find the `prose` class being applied to a `div`. This file is the default layout that `mdx` files use in your application. ```jsx <div className="prose md:prose-xl max-w-screen-md"> {title && <h1 className="text-xl leading-tight">{title}</h1>} {children} </div> ``` Now add `dark:prose-dark` and `dark:md:prose-xl-dark` to the `className` of the `div`: ```jsx <div className="prose md:prose-xl dark:prose-dark dark:md:prose-xl-dark"> {title && <h1 className="text-xl leading-tight">{title}</h1>} {children} </div> ``` Refresh... Nothing happens. No changes. There's another step in the `tailwind.config.js` in the `variants` config add `typography: ['dark']`: ```js module.exports = { darkMode: 'class', purge: { enabled: true, content: ['./src/**/*.tsx'], options: { safelist: ['dark'], //specific classes }, }, theme: { typography: (theme) => ({}), extend: { typography: (theme) => ({ dark: { css: { color: 'white', }, }, }), }, }, variants: { typography: ['dark'], }, plugins: [require('@tailwindcss/typography')], } ``` Voíla! You should see the body text of `http://localhost:3000/hi` become `white` as configured. There are a **lot** of options for customizing the look and feel of your markdown. If you want some inspiration, Lee Rob has done a wonderful job for his personal site and you can [check out the config here](https://github.com/leerob/leerob.io/blob/main/tailwind.config.js#L33-L72). ## Summary Users want dark mode and to set it up with TailwindCSS and Next.js it requires some configuration and basic state management. What you've done so far is just a start, and there is a lot of room to expand on the styles to make your application shine. If you'd like to look more closely at a larger scale full-featured application (the one you are looking at right now in fact), you can [checkout the repository for the egghead website on Github](https://github.com/eggheadio/egghead-next). Here's the [end state of the project you've been working on in this article on Github as well](https://github.com/joelhooks/next-typescript-tailwind-mdx-starter/tree/2-hello-darkness). If you've got any questions, please [ask them on Twitter](https://twitter.com/jhooks)! <EmailSubscribeWidget />
article
<Course slug="graphql-data-in-react-with-apollo-client" /> <div className="prose-reset text-lg font-medium pb-8"> This is going to be a long post about <mark>how to setup a Rails application to serve a GraphQL API</mark>, that is then <mark>consumed using a combination of Apollo, React, and TypeScript</mark> on the frontend. All within the same application. </div> I believe this is a good choice of stack for two main reasons: 1. GraphQL provides a much cleaner query API than a REST API does -- especially because I can request only the data I want at any time. 2. With TypeScript and another utility called `graphql-codegen`, I can ensure the types that are served by my API match exactly to the types used in my frontend at all times. For this post, all the code is written from the perspective of having just run the command to create a new Rails application: ``` rails new books ``` There's no fancy configuration here, just plain Rails. This guide is written in a way that should allow you to apply the same concepts to your existing applications if you have one of those you want to use. This guide is for **intermediate** Rails developers, and it will gloss over a few of the fundamental Rails concepts such as models, migrations, views, routes, and controllers. I will assume you know those by now. What won't be glossed over is the GraphQL, TypeScript, React, and Apollo setup. After all, that's why you're reading this post in the first place. This guide will _feel_ long, but most of it talks about things that are a one-time setup cost. We pay this large cost _now_ so that our application is easier to develop over the much, much longer term. ## JavaScript? In my Rails app? For a long time, there have been efforts to have one flavor or another of JavaScript be a part of Rails itself. It started out with [Prototype.js](http://prototypejs.org/), and moved onto [jQuery](https://jquery.com/), to now a situation where Rails does not thrust its opinion of a JavaScript framework into your application -- you're free to choose. There has been a modern push for Rails applications to integrate further with modern JavaScript frameworks, such as React and Vue. Nowhere is this more evident than the fact that modern Rails applications now include a gem called `webpacker`. This gem provides an interface between the Rails application and any dependencies provided from the frontend by Webpack. You can specify your JavaScript dependencies in files called _packs_, and then load those into your Rails application using ERB code. Brand new Rails applications have a file called `app/javascript/packs/application.js`: ```js // This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. require('@rails/ujs').start() require('turbolinks').start() require('@rails/activestorage').start() require('channels') // Uncomment to copy all static images under ../images to the output folder and reference // them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>) // or the `imagePath` JavaScript helper below. // // const images = require.context('../images', true) // const imagePath = (name) => images(name, true) ``` While these dependencies are typically JavaScript, although they could be CSS or images too. This file is served out of the application via this line in the application layout (`app/views/layouts/application.html.erb`): ``` <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> ``` When you run `rails s` and access `http://localhost:3000`, Rails will compile the Webpack assets and serve them through the Rails server itself. What about webpack-dev-server? If you don't want to wait for a request to tell Webpack to compile assets, you can run <code>bin/webpack-dev-server</code> as a separate process and your assets will be compiled as soon as they change, rather than whenever the page is refreshed. The difference is usually about half a second, but in larger applications, it can be much longer than that. My advice would be to <em>always</em> rely on <code>bin/webpack-dev-server</code>. This `app/javascript/packs/application.js` will be the file that will be the place we load our JavaScript into our application. It doesn't have to be the _only_ place, we could in fact spread this out over multiple different packs, if we wished: ``` <%= javascript_pack_tag 'users', 'data-turbolinks-track': 'reload' %> <%= javascript_pack_tag 'books', 'data-turbolinks-track': 'reload' %> <%= javascript_pack_tag 'checkout', 'data-turbolinks-track': 'reload' %> ``` If we approached it this way, then we could split our code up and only load whatever assets we needed to load on certain pages. Perhaps we only want to load the `users` content on some pages and the `checkout` code on others. For this tutorial, we'll stick with _one_ `application.js` file. We'll return to this `app/javascript/packs/application.js` file later on when we implement some frontend code. Before we need to build our frontend, we'll need to serve some data out of our Rails application. And to serve that data, we're going to use GraphQL. ## Setting up our Rails application Before we get to setup GraphQL, we'll quickly setup a model and some data in our database. Then we'll get to GraphQL. ### Model setup Let's begin by creating a new model within our application and migrating the database to create the table for that model: ``` rails g model book title:string rails db:migrate ``` After this, we'll need to create at least one book so that we have some data to be served through the API: ``` rails c # wait a little bit >> Book.create!(title: "Active Rails") ``` With our model setup with some data, we can now add our GraphQL API, which will serve this data for the model. ## Setting up GraphQL There is a gem called `graphql`, which has all the things we need to have to use GraphQL within our Rails application. Let's add it as a dependency of our application now: ``` bundle add graphql ``` Next up, we can run the installer that comes with that gem: ``` rails g graphql:install ``` This will setup a few classes within our application, and we will use some of these in this guide. Of note are: - `app/graphql/books_schema.rb` - Where the GraphQL schema for our application is defined. - `app/graphql/types/query_type.rb` - Where fields for GraphQL queries are defined. - `app/graphql/types/mutation_type.rb` - Where fields for GraphQL mutations are defined. At the end of this setup, we will see this message: > Gemfile has been modified, make sure you `bundle install` The modification that has been made is that another gem called `graphiql-rails` has been added to our Gemfile, along with two routes to `config/routes.rb`. Let's run `bundle install` before we forget to: ``` bundle install ``` The two routes that were added to `config/routes.rb` are: ```ruby if Rails.env.development? mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql" end post "/graphql", to: "graphql#execute" ``` The first route enables GraphiQL, a graphical interface to GraphQL, which is then accessible in our application at http://localhost:3000/graphiql. The second route is where our GraphiQL and our frontend will send GraphQL queries to. The `GraphqlController` was generated for us by the earlier `rails g graphql:install` invocation. Let's now setup a GraphQL object to represent books in our GraphQL API by running this command: ```shell rails g graphql:object Book ``` This command will inspect our `Book` model and create a GraphQL type that exposes all attributes from that model. It create this file at `app/graphql/types/book_type.rb`: ```ruby module Types class BookType < Types::BaseObject field :id, ID, null: false field :title, String, null: true field :created_at, GraphQL::Types::ISO8601DateTime, null: false field :updated_at, GraphQL::Types::ISO8601DateTime, null: false end end ``` We could remove any of these fields if we did not want to expose them through the GraphQL API. But for now, we'll keep them. To use this type, we can declare a field over in `app/graphql/types/query_type.rb`. We'll delete the example one that is there at the moment and turn this file into this: ```ruby module Types class QueryType < Types::BaseObject field :books, [Types::BookType], null: false def books Book.all end end end ``` Fetching all records from a database considered dangerous Fetching all the records at once in a table might mean you end up with a lot of records. In the past, you might've used something like <a href='https://github.com/mislav/will_paginate'>will_paginate</a> or <a href='https://github.com/kaminari/kaminari'>Kaminari</a> to do pagination in your application. GraphQL uses [connections](https://graphql-ruby.org/pagination/connection_concepts) for this, but we will not be covering that in this guide. This will allow us to query our GraphQL endpoint and retrieve all the books by using this GraphQL query through GraphiQL: ```graphql query allBooks { books { id title } } ``` Well, we could! But `graphiql-rails` is [currently broken](https://github.com/rmosolgo/graphql-ruby/issues/2550) with Rails 6. ### GraphiQL workaround The version of GraphiQL bundled with `graphiql-rails` is broken, and so we will need to work around this problem. Let's start by removing that gem from the `Gemfile`: ``` gem 'graphiql-rails', group: :development ``` And we'll remove the route from `config/routes.rb` as well: ```ruby if Rails.env.development? get '/graphiql', to: "graphiql#index" end ``` An alternative app we can use is the [GraphQL playground](https://www.apollographql.com/docs/apollo-server/testing/graphql-playground/). Download a version for your OS from the [releases page](https://github.com/graphql/graphql-playground/releases/tag/v1.8.10) on GitHub. To make this application work with our Rails application, we'll need to make one little change in the `GraphqlController`. We need to uncomment the `protect_from_forgery` line and turn it into this: ```ruby protect_from_forgery with: :null_session, unless: -> { request.local? } ``` This will ensure that local requests -- requests from the same machine the application is running on are allowed through, but everything else must send through a CSRF token. Our Rails application provides the CSRF token, and we'll see that used a little later on when we get to using Apollo. The CSRF token will be validated by Rails, and only requests that use a valid CSRF token will be permitted to make requests to our API. Load up GraphQL playground and put in `http://localhost:3000/graphql` as the endpoint. In the left panel, enter: ```graphql query allBooks { books { id title } } ``` And then hit the Play button in between the panels. When the request succeeds, we'll see the data come back through from the GraphQL API:  We'll know that we've setup our GraphQL code correctly within the Rails application when we see this. This means we can now proceed to set up the frontend of our application. ## TypeScript + React setup There are two different ways we could go here: 1. We could add React and Apollo to our application and live a happy and fruitful life using JavaScript. 2. We could add React, Apollo, **and TypeScript** to our application and live a happy and fruitful life with an extra guarantee our code will be type-checked, and we won't fall into [the easy trap of comparing a string to a number](https://www.destroyallsoftware.com/talks/wat). I prefer the second route, even if it is a bit more work in the setup. The second path eases the cognitive load involved with remembering the types of things -- like we would have to do in a traditional Ruby or JavaScript application. TypeScript can _tell us_ the types of our variables, especially in an editor like Visual Studio Code, which frankly has _excellent_ TypeScript integration. On top of this, there is another package we'll use later on called Codegen that will generate TypeScript types for us directly from our Ruby GraphQL API. ### TypeScript To start off, we'll add TypeScript to our Rails application, which we can do by running this command: ``` rails webpacker:install:typescript ``` This will: - Add `typescript` and `ts-loader` as dependencies of our application in `package.json`. These packages are used to load and parse TypeScript files, and `typescript` comes with a command called `tsc` that we can use to check if our code is typed correctly. - Create a new file called `tsconfig.json` that contains all the configuration for TypeScript. - Configure Webpacker to load TypeScript files (anything ending in `.ts` or `tsx`), and it'll put a new file in `app/javascripts/packs` called `hello_typescript.ts`: ``` // Run this example by adding <%= javascript_pack_tag 'hello_typescript' %> to the head of your layout file, // like app/views/layouts/application.html.erb. console.log('Hello world from typescript'); ``` We can delete this file, as we won't be needing it. One extra bit of configuration that we'll need to do here is to set a configuration value in `tsconfig.json`. Add this line to the `compilerOptions` list: ``` "jsx": "react" ``` This will direct the TypeScript compiler to use React when it encounters a JSX tag. For more information about this option, [read this documentation page from the TypeScript handbook](https://www.typescriptlang.org/docs/handbook/jsx.html). ### React Next up, we want to add React to our application. We can do this using a `webpacker:install` command too. ``` rails webpacker:install:react ``` This command will: - Create a `babel.config.js` file that contains configuration for Babel directing it how to load React components. - Create a file at `app/javascript/packs/hello_react.jsx` that demonstrates how to use React within our application. - Configures `config/webpacker.yml` to support files ending with `.jsx` - Adds the following JS packages: - `@babel/preset-react` - `babel-plugin-transform-react-remove-prop-types` - `prop-types` - `react` - `react-dom` This `babel.config.js` file that was generated contains some code to load a library called: `babel-plugin-transform-react-remove-prop-types`: ``` isProductionEnv && [ 'babel-plugin-transform-react-remove-prop-types', { removeImport: true } ] ``` PropTypes allows us to specify the types for React components. A small example of this is available in `app/javascript/packs/hello_react.jsx`: ```jsx Hello.defaultProps = { name: 'David', } Hello.propTypes = { name: PropTypes.string, } ``` We will not be using PropTypes in our code because we'll be using TypeScript instead. PropTypes has been succeeded by TypeScript. Why on earth are there <em>two</em> ways to specify types in a React codebase? That might be what you're thinking right now. A little bit of history is that PropTypes has existed for a long time, while TypeScript has gained preference recently. PropTypes allows us to specify that the `name` property for the `Hello` component is going to be a string. When we load this code in the browser, PropTypes will run and then validate that `name` is indeed a string. If it's not, then we'll see an error appear in the developer console (if we're looking there!). This is what we'd call a <em>runtime</em> type check -- the code is type-checked when it runs. TypeScript allows us to do the same sort of validation, but it will run at <em>compile time</em>, right when the code is being "translated" into JavaScript for the browser's consumption. This is the right step (imo) because while you're writing the code, you want to know if you've made a mistake -- not when you're running it! The other advantage is that TypeScript has excellent editor integration, and it will warn you about incorrect types. We'll see a few of these examples later on in this guide. So let's remove this configuration from `babel.config.js`, as well as removing the `prop-types` and associated babel plugin: - `yarn remove prop-types babel-plugin-transform-react-remove-prop-types` This will mean that the packages that have been added by `webpacker:install:react` are now just: - `@babel/preset-react` - `react` - `react-dom` The `@babel/preset-react` package configures Babel to parse JSX content into regular JavaScript code, and a few other niceties that we don't need to care about right now. The two other packages, `react` and `react-dom`, are the most useful of the lot, as they allow us to use React and have it interact with a page's DOM (Document Object Model). This work is separated into two packages, as React can be used in other contexts outside of a DOM, such as [React Native](https://reactnative.dev/). Let's take a closer look at what `app/javascripts/packs/hello_react.jsx` contains: ```jsx // Run this example by adding <%= javascript_pack_tag 'hello_react' %> to the head of your layout file, // like app/views/layouts/application.html.erb. All it does is render <div>Hello React</div> at the bottom // of the page. import React from 'react' import ReactDOM from 'react-dom' import PropTypes from 'prop-types' const Hello = (props) => <div>Hello {props.name}!</div> Hello.defaultProps = { name: 'David', } Hello.propTypes = { name: PropTypes.string, } document.addEventListener('DOMContentLoaded', () => { ReactDOM.render( <Hello name="React" />, document.body.appendChild(document.createElement('div')), ) }) ``` Now that we've taken out the `prop-types` library, we can remove all the propTypes code from this file: ```jsx import React from 'react' import ReactDOM from 'react-dom' const Hello = (props) => <div>Hello {props.name}!</div> document.addEventListener('DOMContentLoaded', () => { ReactDOM.render( <Hello name="React" />, document.body.appendChild(document.createElement('div')), ) }) ``` That's much easier to read now! This file imports both the `React` and `ReactDOM` libraries. We need to import `React` wherever we're using JSX. And we import `ReactDOM` whenever we want to put a React component somewhere on our page. Next, this file defines a small function component, returning a simple `<div>` with a message inside it. Finally, this code waits for the `DOMContentLoaded` event to be sent out by the browser, and then it will append this component to the `<body>` tag of whatever page has included this JavaScript. ### Rendering React within Rails Let's take a look at how to render this React component within our Rails application. To get started, we'll create a new controller, view, and route by running this command: ``` rails g controller home index ``` The route this generates will be in `config/routes.rb` and will look like this: ```ruby get 'home/index' ``` Let's change this to be a `root` route so that we can visit it using http://localhost:3000/ instead of http://localhost:3000/home/index. ```ruby root to: "home#index" ``` Once this route has been changed, we can go to http://localhost:3000 and see the view that was generated:  This view is not currently rendering our React component, but we can make it do so by bringing in the `hello_react.jsx` file with this addition to `app/views/home/index.html.erb`: ``` <%= javascript_pack_tag "hello_react" %> ``` When we refresh the page, we'll see the React component appended to the bottom of the page:  Excellent! We now have a way to make React components appear on our Rails views. However, there's a caveat to this: these components will _always_ appear at the _bottom_ of our pages! If we were to add a footer to the bottom of the `<body>` tag within our application layout, these React components would appear underneath that footer. That is not ideal! What would be better for us is to be able to insert these components wherever we wish on the page. This will enable us to have Rails-generated HTML sitting along-side React components that also generate their own HTML. So to work around that, we'll devise a way to mount React components at particular places within Rails views. ### Placeable React components What we now want to be able to do is to be able to put a React component anywhere in our view. Let's say that we wanted our "Hello React!" to appear _between_ the `h1` and `p` tags in `app/views/home/index.html.erb`: ``` <h1>Home#index</h1> <%# React component goes here %> <p>Find me in app/views/home/index.html.erb</p> ``` We cannot put `javascript_pack_tag` there, as the code in `hello_react.jsx` will still direct the component to be appended to the `body` tag: ```jsx document.addEventListener('DOMContentLoaded', () => { ReactDOM.render( <Hello name="React" />, document.body.appendChild(document.createElement('div')), ) }) ``` So what can we do instead? Well, another way we can approach this problem is to have our code look for particular types of elements on the page, and then choose to put React components into those particular elements. For example, we can make it so if we were to write this code: ``` <h1>Home#index</h1> <div data-react-component='Hello'></div> <p>Find me in app/views/home/index.html.erb</p> <%= javascript_pack_tag "hello_react" %> ``` A component called `Hello` would be added between those `<h1>` and `<p>` tags. To put this little `div` tag inside our views, we can write a helper in `app/helpers/application_helper.rb`: ```ruby module ApplicationHelper def react_component(component_name) content_tag( "div", data: { react_component: component_name } ) { "" } end end ``` This code in `app/views/home/index.html.erb` will generate that `div`: ``` <%= react_component "Hello" %> ``` If we wanted to support parsing properties to this method, we could make this code: ```ruby module ApplicationHelper def react_component(component_name, **props) content_tag( "div", data: { react_component: component_name, props: props.to_json, } ) { "" } end end ``` This takes a list of properties and passes them through as an extra `data-props` attribute on our `div`, and so allows us to write code such as: ``` <%= react_component "Hello", { name: "React" } %> ``` However, if we go and refresh that page again, we'll see the component is not being rendered in that spot -- it's still being rendered at the bottom of the page:  But if we inspect the source code for our page, we'll see that the `<div>` _exists_`: ```html <div data-react-component="Hello"></div> ``` In order to fix this up, we're going to need to write some additional code that will scan for these tags containing the `data-react-component` attribute and then act on those tags. ### Scanning for and mounting React components The code that we're going to use to do this scanning and mounting the React components is the most complicated code we'll come across in this guide. Please bear with me! What we'll do here is work on making this code work, then we'll go through it top-to-bottom. We'll put this code in a file called `app/javascript/mount.tsx`: ```tsx import React from 'react' import ReactDOM from 'react-dom' export default function mount(components = {}) { document.addEventListener('DOMContentLoaded', () => { const mountPoints = document.querySelectorAll('[data-react-component]') mountPoints.forEach((mountPoint) => { const dataset = (mountPoint as HTMLElement).dataset const componentName = dataset['reactComponent'] const Component = components[componentName] if (Component) { const props = JSON.parse(dataset['props']) ReactDOM.render(<Component {...props} />, mountPoint) } else { console.log( 'WARNING: No component found for: ', dataset.reactComponent, components, ) } }) }) } ``` And over in `app/javascript/packs/application.js`, we'll add these lines: ```js import mount from '../mount' import Hello from './hello_react' mount({Hello}) ``` Lastly, we'll need to export the `Hello` component from `app/javascript/packs/hello_react.js`: ```jsx import React from 'react' import ReactDOM from 'react-dom' export default (props) => <div>Hello {props.name}!</div> ``` With this change to `hello_react.js`, we've removed the code that was previously automatically inserting the component at the bottom of the page, and instead, we're now exporting this component and leaving the rendering of that component as something else's job. That _something else_ is that `mount.tsx` code that we wrote. Let's look at that again, step by step: ```tsx export default function mount(components = {}) { document.addEventListener("DOMContentLoaded", () => { const mountPoints = document.querySelectorAll("[data-react-component]"); ``` This code defines the `mount` function that we use in `application.js`. This function adds an event listener that waits for the `DOMContentLoaded` event to happen, just like the old code we had in `hello_react.js` did. Then we go a different path from there. Instead of rendering a _specific_ React component, we're instead going on a search for which ones the page wants us to render. We find all the elements that are "mount points" for our React components by using `querySelectorAll` and looking for those elements that match the CSS selector `[data-react-component]`. Let's look at the next couple of lines: ```tsx mountPoints.forEach((mountPoint) => { const dataset = (mountPoint as HTMLElement).dataset; const componentName = dataset["reactComponent"]; const Component = components[componentName]; ``` We attempt to find out their component name for all of the elements mentioned by accessing the `data-react-component` property by using a combination of `dataset` and `["reactComponent"]`. Once we have that name, we can then attempt to find that component by a name using `components[componentName]`. As long as we've chosen to mount a component in `application.js` with this function, it will be available here. Let's look at the final few lines: ```tsx if (Component) { const props = JSON.parse(dataset['props']) ReactDOM.render(<Component {...props} />, mountPoint) } else { console.log('WARNING: No component found for: ', componentName, components) } ``` If this code finds a component, it attempts to parse the json contained in `dataset["props"]`. This will pull out the JSON from the `data-props` attribute on the `<div>`: ```html <div data-react-component="Hello" data-props='{"name":"React"}'></div> ``` Then, now that the `mount` function has all three of the `mountPoint`, the `Component` and the `props` determined, it can use `ReactDOM.render` to put this code directly onto the page, exactly where we said it should go. Let's refresh the page. This time we'll see the component is now in between the `<h1>` and `<p>` tags:  Hooray! We now have the ability to put our React components wherever we like on the page. This will enable us to intermingle our Rails view code with React components -- we can put static HTML rendered server-side by Rails right next to dynamic HTML rendered client-side by React. ## Books React Component Let's now look at something a bit more complex than putting "Hello React!" on the page. This time, we're going to build another component, called `Books`. This component will render hard-coded data from a TypeScript file onto `div` tags on the page. When we write this file, we'll be declaring types using TypeScript and using those to guide us in what properties are available inside each of the components we build. We'll eventually use this file to pull in and display the data from our Rails application's GraphQL. Before we get there, though, it will help to build a scaffold using static data so that we can experiment with it, if necessary. Let's create a new file at `app/javascripts/Books/index.tsx`. ```tsx import React from 'react' const data = { books: [ { id: '1', title: 'Active Rails', }, ], } const loading = false const Book: React.FunctionComponent = ({title}) => { return <li>{title}</li> } const Books = () => { if (loading) { return <span>"Loading..."</span> } return ( <div> <h1>Books</h1> <ul> {data.books.map((book) => ( <Book {...book} key={book.id} /> ))} </ul> </div> ) } export default Books ``` In this file, we start by importing React. This is necessary because we're using JSX in this file. Next, we define the shape of the data that will be coming through to our component, mimicking the shape of the data that GraphQL gives us. Next, we define a `Book` component that will render a simple `<li>` tag with a book's title. Then we get to the `Books` component. This one uses the `loading` and `data` variables set outside of the component to pretend like it's loading data from our GraphQL service and then uses the `Book` component to render that data. Finally, the `Books` component is exported as the default export. This will allow us to import it into other files using `import Books from "./Books"`. What we have here are the barest of bones required to render data using React and TypeScript in our application. This is just a few steps up from our "Hello React" example and moves us closer towards having this frontend talk to our GraphQL backend. ### Mounting the Books component To use this component, we will need to mount it within our application. We can do this by going to `app/javascript/application.js` and changing the end of that file to this: ``` import Hello from "./hello_react"; import Books from "../Books" mount({ Hello, Books }); ``` This will now automatically render our `Hello` and `Books` components whenever they're requested through our application. To request the `Books` component to be rendered, we'll go over to `app/views/home/index.html.erb` and add this line in: ``` <%= react_component "Books" %> ``` Now when we refresh this page, we'll see our (very short!) list of books:  Success! The Books component is now rendering on the page. One of the great things about this Webpacker setup that we have got going is that if you edit the code in `Books/index.tsx` and save the file, the browser will automatically refresh. Go ahead and try it out now! The component is still working with data that we've coded in ourselves. The next piece of this puzzle is to configure the frontend code so that instead of pulling the data in from a hardcoded source, it pulls it in from the GraphQL API provided by Rails. We can do this using a JavaScript package called Apollo. ## Apollo The [Apollo Client](https://www.apollographql.com/docs/react/) is a widely-used package that is used to provide an easy way of communicating between the frontend and a GraphQL API. We'll use this package to replace the hard-coded data within `Books/index.tsx`. ### Setting up Apollo To get started, we will need to add the `@apollo/client` and `graphql` packages as a dependency. We can do that with this command: ``` yarn add @apollo/client graphql ``` If you're running `bin/webpack-dev-server`, make sure to restart it at this point to make sure it can load the new dependencies. Next, we will need to configure this Apollo Client to speak to our GraphQL API. We can do that by creating a new file at `app/javascript/graphqlProvider.tsx` and putting this code inside it: ```tsx import React from 'react' import { ApolloClient, InMemoryCache, ApolloProvider, HttpLink, } from '@apollo/client' const csrfToken = document .querySelector('meta[name=csrf-token]') .getAttribute('content') const client = new ApolloClient({ link: new HttpLink({ credentials: 'same-origin', headers: { 'X-CSRF-Token': csrfToken, }, }), cache: new InMemoryCache(), }) export const withProvider = ( WrappedComponent: React.ComponentType, props: any = {}, ) => () => { return ( <ApolloProvider client={client}> <WrappedComponent {...props} /> </ApolloProvider> ) } ``` This code does two main things. The first thing is that it defines `client`, which sets the groundwork for how Apollo is configured to connect to our API. By using `HttpLink`, and _not_ passing it a URL, Apollo will default to making requests to `/graphql` -- which is exactly where our GraphQL API is hosted. This `client` variable uses the `csrfToken` from the page as well, ensuring that the requests pass the CSRF protections built into the `GraphqlController` for our Rails application. If we did not do this, in a production environment, users would not be able to make requests through to our GraphQL API as Rails would block their attempts due to null CSRF tokens being passed in. The second thing this code does is the `withProvider` variable. This function wraps a passed in component in the `ApolloProvider` component, allowing that wrapped component to make calls to the GraphQL API. ### Using Apollo in our Books component With this code setup, we can now turn our attention back to `Books/index.tsx`. We want to convert this code to do a GraphQL query to load its data. We can start this process by defining a GraphQL query at the top of this file: ```tsx import React from 'react' import gql from 'graphql-tag' const booksQuery = gql` query allBooks { books { title } } ` ``` To use this query, we can use the `useQuery` hook function from Apollo. We must first import it: ```tsx import {useQuery} from '@apollo/client' ``` Then we can use it inside the `Books` component: ```tsx const Books = () => { const {data, loading, error} = useQuery(booksQuery) if (loading) { return <span>Loading...</span> } return ( <div> <h1>Books</h1> <ul> {data.books.map((book) => ( <Book {...book} key={book.id} /> ))} </ul> </div> ) } ``` Note that for the most part, the API is the same. We are still using the `loading` variable, and the data is available at `data.books`. The last thing to do here is to use the `withProvider` function to wrap the `Books` component. First, we'll need to import it. ```tsx import {withProvider} from '../graphqlProvider' ``` Then we can wrap our `Books` component when we export it: ```tsx export default withProvider(Books) ``` This will make it so that the `Books` component has access to the Apollo client we have configured, and that will mean the `Books` component will be able to run its GraphQL query. When we refresh the page now, we'll see that the data is being loaded from our API! We've now successfully connected our first React component back through to our GraphQL API. We're not completely done yet. There's one more issue hanging around. That issue is that the `data` variable that is coming back from our query is completely untyped. I can see this in Visual Studio Code by hovering my cursor over `data`. Here's what I see:  This is problematic, because it means that we're not having the properties we call on `data` be typechecked. This means we can write this code: ```tsx return ( <div> <h1>Books</h1> <ul> {data.notBooks.map((book) => ( <Book {...book} key={book.id} /> ))} </ul> </div> ) ``` And TypeScript won't tell us that `notBooks` is not a part of the returned data. Further to this, the `book` type is _also_ `any`, and the correctness of that data is only enforced by the earlier `BookType` declaration we made earlier, and that we're still using in the `Book` component. We need to rectify this and ensure that we have accurate types from our data right from the moment they come out of the API responses. ## Sharing types between backend + frontend In this final section, we'll make it so that we can have our frontend read and understand the types specified by our backend. We will do this by using a combination of features from the `graphql` gem, as well as a series of JavaScript packages from the `@graphql-codegen` family. When we write GraphQL queries, we must specify the types for all the fields. For example, over in `app/graphql/types/book_type.rb` we specify the types like this: ```ruby module Types class BookType < Types::BaseObject field :id, ID, null: false field :title, String, null: true field :created_at, GraphQL::Types::ISO8601DateTime, null: false field :updated_at, GraphQL::Types::ISO8601DateTime, null: false end end ``` These types are here so that we know what kind of data we're working with. We know that `title` is going to be a string and that `created_at` is _also_ going to be returned as a string... except it's a string formatted as an `ISO8601` timestamp as indicated by its special typing. We want these types in our React code so that we can be sure we're working with them correctly. But these types are in Ruby, not in JavaScript. So how do we get them out of Ruby, and into JavaScript? The way we can do this is with a Rake task built into the `graphql` gem itself which will allow us to dump the GraphQL schema out to a particular file. This schema will be a JSON representation of our GraphQL API, and enables [introspection](https://graphql.org/learn/introspection/) of the API. If you've ever wondered how GraphQL apps like GraphQL Playground and GraphiQL know what fields are available, this is how! The application reads that schema, and from that, it will know the fields and their types. We can dump the schema for this application by using a Rake task that is built into the `graphql` gem. That task needs some configuration so that it can find out where our Ruby schema is, and where to dump the JSON schema definitions to. Once we have that schema dumped, we can generate types from that dump by using a JavaScript package called `codegen`. ### Dumping types from the GraphQL backend Let's start by dumping the types from the backend using a Rake task. Let's create this Rake task and specify its configuration, adding these lines to the `Rakefile` within our application: ``` require "graphql/rake_task" GraphQL::RakeTask.new( schema_name: "BooksSchema", directory: "./app/javascript/graphql", dependencies: [:environment] ) ``` The `GraphQL::RakeTask.new` initializer is responsible for registering the Rake task with Rake. The `schema_name` option tells it where to find the schema, and this name _must_ match the schema class name in `app/graphql`. It's the name of your application, followed by the word "Schema", typically. The `directory` option tells this Rake task where we want to put the JSON schema definitions. And finally, `dependencies` tells the Rake task first to run the `environment` Rake task. This `environment` Rake task is responsible for loading the Rails application environment, and it will load the `BooksSchema` class as a part of that work. With the Rake task setup, we can now run it by running this command: ``` rake graphql:schema:dump ``` This command will read our schema -- written in Ruby -- and convert it into a JSON file, which can be read by JavaScript. ### Generating types from the dumped schema Now that we have our schema dumped out, we can load it in using a package called `@graphql-codegen/cli`. We will need to install this package first: ``` yarn add -D @graphql-codegen/cli ``` Once this package has been installed, we can run another command to configure it. This configuration will ensure that Codegen works exactly as we want it for our application. We can kick off this configuration step by running: ``` yarn graphql-codegen init ``` This command will prompt us for a few separate things: 1. **Application built with**: Choose "React" 2. **Schema**: `app/javascript/graphql/schema.graphql` 3. **Operations and fragments**: `app/javascript/**/*.tsx` 4. **Plugins**: Leave default selected 5. **Output path**: `app/javascript/graphql/types.tsx` 6. **Generate introspection file**: Choose "no" because the `graphql` gem has done this already with the Rake task we just ran. 7. **Name config file**: Leave it as the default, `codegen.yml` 8. **Script in package.json**: `gql:codegen` Why not use a URL for schema? You might've noticed that the default option for "Schema" above is a URL. We <em>could</em> put in http://localhost:3000/graphql here, and Codegen would still work. The only thing about that is that we must have a Rails server running at all times to have our Codegen command work. I think it's better having a schema file that is generated through a Rake task, and then you don't have to remember to run a Rails server. You might think differently, though! And that's alright too. This `init` script will then install more `codegen` packages that will assist us. These packages will appear within the `package.json` `devDependencies` list: - @graphql-codegen/typescript - @graphql-codegen/typescript-operations - @graphql-codegen/typescript-react-apollo These packages are the ones that will be used to generate the types for our TypeScript code. The `codegen` series of packages will do this by reading from the `schema.graphql` file that was dumped from the `rake graphql:schema:dump` Rake task. The way to make `codegen` generate these types is by running the `package.json` script `gql:codegen`: ``` yarn gql:codegen ``` This command will read that `schema.graphql` file and generate TypeScript types into `app/javascript/graphql/types.tsx`. Note that this will only read from the schema file generated by `rake graphql:schema:dump` rather than constantly being updated by the backend automatically. So you will want to get into the habit of running both the Rake task and the Yarn command at the same time: ``` rake graphql:schema:dump && yarn gql:codegen ``` Let's go through what each of these Codegen packages provides us, to better understand what we're getting out of using this tool. ### Codegen + TypeScript The first package, `@graphql-codegen/typescript`, generates TypeScript types from objects in the schema. If we go to `app/javascript/graphql/types.tsx`, here's a couple of the types that we will see: ```tsx export type Scalars = { ID: string String: string Boolean: boolean Int: number Float: number /** An ISO 8601-encoded datetime */ ISO8601DateTime: any } export type Book = { __typename?: 'Book' createdAt: Scalars['ISO8601DateTime'] id: Scalars['ID'] title?: Maybe<Scalars['String']> updatedAt: Scalars['ISO8601DateTime'] } ``` First, there are some scalars that define shortcuts to common types. These are used a little further down when the `Book` type is defined to specify the types of fields that are available for `Book` objects according to our API. You will notice there that the `title` property is specified with a question-mark. That means that this property can be missing completely from the returned object. These types provide us the groundwork for types in our application's TypeScript code. If we were to use these, we could leverage the shared types between the backend and the frontend. Our frontend _couldn't_ use types that aren't correct according to the backend. But this picture is not complete without the two other packages here, so let's cover those first before we look into how we can use those types. ### Codegen + TypeScript + GraphQL Operations The second package, `@graphql-codegen/typescript-operations`, generates TypeScript types from the operations and fragments we've specified in our TypeScript code. An example of an operation is this query in `app/javascript/Books/index.tsx`: ```tsx const booksQuery = gql` query allBooks { books { title } } ` ``` The `@graphql-codegen/typescript-operations` package scans our TypeScript files for these operations and will generate corresponding types for them. If we go to `app/javascript/graphql/types.tsx`, we'll see the generated types for this query: ```ts export type AllBooksQueryVariables = Exact<{ [key: string]: never; }>; export type AllBooksQuery = ( { **typename?: 'Query' } & { books: Array<( { **typename?: 'Book' } & Pick<Book, 'title'> )> } ); ``` The first type here says that the `allBooks` query does not take any variables. The second type specifies that when the `AllBooksQuery` returns data, it does so with a key called `books`, and that the value for that `books` key will be an array of items that are shaped as the `Book` type specifies, but _just_ the `title` field from that type -- as indicated by `Pick<Book, 'title'>`. This type can be used to ensure that we're only accessing data that our GraphQL query returns. The second type here specifies that _yes_ the query _does_ return an array of books... but it also says that the information that will come from that query _only_ consists of the `title` field. There is no other field there. We can use this second type in our code by specifying it as a generic in `Books/index.tsx`: ```tsx const {data, loading, error} = useQuery<AllBooksQuery>(booksQuery) ``` This says to `useQuery`, that the type of data being returned by this function will match the shape specified by `AllBooksQuery`. If we look a little further down in our file, we'll see that the code is failing because we're trying to access the `id` property from a `Book` object:  We're seeing this message from TypeScript because our type for `AllBooksQuery` does not specify that books returned from that query have an `id` property. TypeScript is smart enough to know that we're making a mistake here, and it quickly points it out! We can fix this by adding an `id` field to the query in `Books/index.tsx`: ```tsx const booksQuery = gql` query allBooks { books { id title } } ` ``` And then by regenerating the types using: ``` yarn gql:codegen ``` This last command updates the `AllBooksQuery` type to this: ```tsx export type AllBooksQuery = {__typename?: 'Query'} & { books: Array<{__typename?: 'Book'} & Pick<Book, 'id' | 'title'>> } ``` This is a type that now specifies that `Book` can have `title` _and_ `id` specified. If we look back at the place where the error previously was occurring, we'll now see that it is fine:  This is the benefit that we get out of using `@graphql-codegen/typescript-operations`. This package inspects the queries that are used in our application, and it will generate types from them. Those types can then be used by TypeScript to inform us if we're requesting correct or incorrect properties. ### Codegen + TypeScript + React + Apollo The final package that is added by Codegen's `init` script is one called `@graphql-codegen/typescript-react-apollo`. This package brings together all of the previous parts into one very neat cohesive whole. This package does not provide us with types, but instead it provides us with functions. Specifically, it provides us with hooks that we can use in our React components to shortcut the necessity of specifying `AllBooksQuery` or `AllBooksQueryVariables` as type arguments. Here's one of the functions it provides us: ```tsx export function useAllBooksQuery( baseOptions?: Apollo.QueryHookOptions<AllBooksQuery, AllBooksQueryVariables>, ) { return Apollo.useQuery<AllBooksQuery, AllBooksQueryVariables>( AllBooksDocument, baseOptions, ) } ``` We can call this function in `Books/index.tsx` by first importing it: ```tsx import {useAllBooksQuery} from 'graphql/types' ``` And then using it in place of our previous `useQuery` invocation in that same file: ```tsx const Books = () => { const { data, loading, error } = useAllBooksQuery(); ``` Isn't this much nicer than what we just had there? By invoking this function, we are getting Codegen to do the heavy lifting of specifying the type arguments for us. If we did not have Codegen doing this, then we would need to write it all out ourselves. A full query, including query variables, would need to be written like this: ```tsx const Books = () => { const { data, loading, error } = useQuery< AllBooksQuery, AllBooksQueryVariables >(AllBooksDocument, baseOptions); ``` That is quite messy and would require us to import all of these different things into this file. Instead of doing that, we can use `@graphql-codegen/typescript-react-apollo` and that will provide us small functions like `useAllBooksQuery` that we can use to ensure we have accurate types from the backend all the way through to the frontend. To ensure that this is working as intended, we'll try to replicate that "Property 'id' is missing" error we saw before. We can replicate that error by removing the `id` field from the `booksQuery` in `Books/index.tsx`: ```tsx const booksQuery = gql` query allBooks { books { title } } ` ``` Next, we'll run `yarn gql:codegen` to regenerate the types for this query. Once that command completes, we'll see that the `id` property is missing again:  Excellent! This means that it is all working as it should. ## What we've accomplished By using the `graphql` gem within the Ruby part of our Rails application, we've been able to expose data from our database through a GraphQL API. We then read that data using a combination of React, Apollo, and TypeScript on the frontend. When we're using TypeScript, we need to be able to know the types of our data. This will ensure that our program is as correct as it can be. While we _could_ define these types ourselves -- as we saw earlier on when we were setting up TypeScript -- it is instead better to automatically generate them from the GraphQL API's types instead. The way we do this is with a combination of the `graphql` gem's Rake task (defined in `Rakefile`), and another command called `yarn gql:codegen`. The latter command outputs types to `app/javascript/graphql/types.tsx`, and then it's from that file we can import things like the `useBooksQuery` function and `Book` type, if we require it. One other thing to remember is that thanks to the `@graphql-codegen/typescript-operations` All of this work is designed to set a solid foundation for a GraphQL API. <Course slug="graphql-data-in-react-with-apollo-client" />
course
On the surface, starting a project sounds easy. First you make some directories, install some dependencies, then you write some code. But there's a bit more to it than just those three steps. The type of project you're working on impacts the decisions you make. It gets more complicated when you're working on multiple projects that are related. For example, maybe you have a customer-facing frontend app, an admin dashboard app, and a single backend used for both. How does this change your directory structures? How should you share code between projects? What happens when you add a Design System into the mix? It can get hard to keep things straight in your head. Nx is a tool that aims to solve these problems for you, whether you're working solo on a small full-stack app or on a dev team of thousands. It's not just an opinionated folder structure. When you create an app with Nx, it generates unit and e2e test setups as well as preparing bundling and code-splitting with Webpack, and stubbing out common features like routing. One of the coolest features of Nx is its Dependency Graph. The graph can visually show you the relationship between the parts of your application, and is optimized to ensure that compiling, testing, and linting only happens in the affected areas of your project. In this course, Juri Strumpflohner demonstrates these features and more through the iterative creation of a React + Storybook + Express app. Don't worry if this isn't your preferred stack! Nx supports the most popular frameworks & libraries on the web. More importantly, the focus of this course is more on the workflow than the implementation. Watch Juri's course, and see if the Nx tooling & workflow is right for you and your team!
course
In this course we will begin with nothing more than an empty directory & a text editor. Through small, focussed lessons we’ll learn how to setup our app with Webpack & Babel and how to configure these tools for use with Preact. Then we’ll move on to learning how to create components and how the Preact API mirrors that of React - highlighting the differences/additions along the way. Finally we’ll look at the interoperability with existing popular libraries in the React community such as Redux & React Router and with the popular development tools such as Redux Dev Tools & React Dev-Tools
course
Today, you can't do anything in JavaScript without bumping into a CLI. Want to install a library? `yarn` add it. Want a React app? `create-react-app`. Want to format your JavaScript? `prettier --write`. Want your types checked? `tsc`. Bundling? Pick from `webpack`, `rollup`, or `parcel`. Deploying? `now` or `netlify deploy`. CLI's are everywhere, and even if you don't write them, sooner or later you'll have to debug them. This workshop serves as a comprehensive survey of the state of the art of CLI tooling for everyone looking to make an impact in open source, across their company, and even in their own productivity. Check out these [**community notes for this course on Github**](https://github.com/eggheadio-projects/build-custom-cli-tooling-with-oclif-typescript-notes).
course
Building an application with React typically involves several tools. Whether you configure these on your own or use a tool meant to save you from the configuration like Create React App, the tools are still there. When you come up against a situation where you need to start from scratch or make changes to a webpack or babel configuration, it helps to understand what each tool does, how they fit together, and how they are configured. In this course, we’ll start from an empty directory and by the end, we will have configured a slim but powerful boilerplate project. Along the way, we’ll touch on each of the major tools and build up to the final setup to gain an understanding of each tool’s purpose and how they all work together to help you build and deliver an application.
podcast
<p>John Lindquist, co-founder of egghead.io, interviews Michael Jackson, co-creator of the react-router library, and co-founder of React Training. Michael discusses his experiences with running a massively popular repo with a relatively small code-base, pioneering of new features, and the future of CDN based importing.</p><p>Michael gets into the early days of the react-router repo, and what he had to do to steward the library. "In open-source, you are not just coding all day." It's mostly management, with it being a relatively small code-base that had a lot of users created a situation where you had to have excellent communication and a lot of deliberateness with what you change.</p><p>React is just Javascript, meaning that it enables multiple solutions and allows innovation within the library. It also means that there will be some discourse in the direction that things should go. Michael also discusses how to keep an open dialogue with the React community, even though doing so may pose some challenges.</p><p>Michael is extremely excited about the future of the CDN and unpkg. He says that it would be awesome if Facebook or Pinterest only needed to load the package once, or even if individual modules were loaded instead of entire libraries. unpkg is excellent and predictable. No need to read the documentation on how to include the library in your app. No need to worry about builds, webpack, bundling. It brings back a fresh perspective and lets you just use the web!</p><hr /><h3>Transcript</h3><p><a href="https://egghead.simplecast.com/episodes/cef87f81/transcript">"React Router with Michael Jackson" Transcript</a></p><h3>Resources</h3><ul><li><a href="https://reacttraining.com/">React Training</a></li><li><a href="https://unpkg.com/#/">unpkg</a></li></ul><h3>Michael Jackson</h3><ul><li><a href="https://medium.com/@mjackson">Medium Blog</a></li><li><a href="https://twitter.com/mjackson?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a></li><li><a href="https://github.com/mjackson">GitHub</a></li></ul><h3>John Lindquist</h3><ul><li><a href="https://twitter.com/johnlindquist?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a></li><li><a href="https://egghead.io/instructors/john-lindquist">egghead.io</a></li><li><a href="https://github.com/johnlindquist">Github</a></li><li><a href="https://johnlindquist.com/">Website</a></li></ul>
podcast
<p>Joel Hooks co-founder of egghead.io, interviews Dan Abramov, co-author of Redux. They discuss the "Redux phenomenon" and the notion of improving the developer experience.</p><p>Dan's Redux course has been the most popular course on egghead.io for years. What caused Redux to blow up as it did? Dan is here today to talk about the problems he faced that inspired him to write this framework, and all the experiences he had that led to it.</p><p>Joel and Dan talk about how quickly functional programming concepts pushed their way into the mainstream. When they were younger object oriented was how you programmed, Gang of Four was like their bible. However, Dan talks about the problems he was facing and how they inspired him to create Redux.</p><p>Dan's belief that user experience starts with the developer also inspired Redux. The notion that a developer should suffer is silly. Having a tool that is a joy to use and allows a programmer just to create things is invaluable.</p><p>The frustration of getting started with React was enormous. You had to deal with Webpack and install packages manually and hope that you didn't mess up. All this was hugely daunting for beginners especially. create-react-app was the solution for that. Allowing an easy way to get React going with a dev server and all, it let you just get in there and start building components.</p><p>Finally, Joel and Dan leave us with a note to those seeking to learn to program well. Read GitHub like it's a blog. Read the commits, the issues, the PR's, all of it. You might not understand what is going on now, but you will build fluency and eventually you'll understand well enough that you can start to answer questions and contribute.</p><hr /><h3>Transcript</h3><p><a href="https://egghead.simplecast.com/episodes/e5759ea0/transcript">"Dan Abramov, co-author of Redux" Transcript</a></p><h3>Resources</h3><ul><li><a href="https://egghead.io/courses/getting-started-with-redux">Getting Started with Redux</a></li><li><a href="https://egghead.io/courses/building-react-applications-with-idiomatic-redux">Building React Applications with Idiomatic Redux</a></li><li><a href="https://en.wikipedia.org/wiki/Design_Patterns">Gang of Four</a></li><li><a href="http://gameprogrammingpatterns.com/">Game Programming Patterns</a></li></ul><h3>Dan Abramov</h3><ul><li><a href="http://twitter.com/dan_abramov">Twitter</a></li><li><a href="https://github.com/gaearon">Github</a></li><li><a href="https://medium.com/@dan_abramov">Blog</a></li></ul><h3>Joel Hooks</h3><ul><li><a href="https://twitter.com/jhooks">Twitter</a></li><li><a href="http://joelhooks.com/">Website</a></li></ul>
lessonDuration 5m 54sFree
Setup a TypeScript + React project from scratch using webpack. Learn the reason behind every line that you need to type and become an expert.
lessonDuration 1m 34sFree
In this lesson I show how to use webpack to code split a modal component in VueJS. Code splitting is a useful tool to help eliminate unused code and only load what's necessary. **Additional Resources** https://vuejs.org/v2/guide/components-dynamic-async.html https://medium.com/js-dojo/3-code-splitting-patterns-for-vuejs-and-webpack-b8fff1ea0ba4
lessonDuration 2m 40s
In this lesson I show how to use webpack to code split based on route in VueJS. Code splitting is a useful tool to help eliminate unused code and only load what's necessary. *Additional Resources* https://router.vuejs.org/en/advanced/lazy-loading.html
lessonDuration 2m 26s
[create-react-app version 2.0](https://reactjs.org/blog/2018/10/01/create-react-app-v2.html) added a lot of new features. One of the new features is added the [svgr](https://github.com/smooth-code/svgr) webpack loader to wrap SVGs in React components as a named export. This let’s you either grab the filename from the default export or grab a wrapped SVG component depending on your needs.
lessonDuration 1m 15sFree
Starting a brand new project can be tricky. Sometimes we end up spending a couple of hours writing configs for tools like webpack, where instead we would like to dive straight to the code. [Parcel](https://parceljs.org/getting_started.html) allows us to quickly start a brand new JavaScript web application without having to worry about writing any configs. In this lesson we are going to learn how to install parcel and how to create a development/production build of our app.
lessonDuration 2m 48sFree
In this lesson, we start a new React project using `create-react-app`. This allows us to not have to worry about tooling like webpack, babel etc. Once installed, we'll remove some of the files we don't need, add some CSS for our project, so we're ready to get started.
lessonDuration 3m 27sFree
# Up and Running with Parcel JS In this video, we will get up and running with Parcel by creating a simple Hello World application in JavaScript. ## What is Parcel? Parcel is a zero configuration web application bundler and Webpack alternative. It supports a ton of functionality out of the box, including Code Splitting, Hot Module Replacement, Environment Variables, and Automatic Transforms for Babel, PostCSS, and PostHTML. ## Asset Support It supports nearly any type of asset you would typically use in a JavaScript project, including: * HTML * Images * Fonts * JavaScript * TypeScript * CoffeeScript * Vue * ReasonML * CSS * SCSS * LESS * Stylus * JSON * GraphQL * Rust * WebAssembly * YAML * TOML * OpenGL * Pug * WebManifest Learn more at [Parcel's website](https://parceljs.org/getting_started.html).
lessonDuration 30sFree
Learn how to import static assets into components in alternative scenarios when it might be necessary, like if you couldn't use webpack. [Assets added to the static folder won't leverage Gatsby's performance optimizations](https://www.gatsbyjs.org/docs/static-folder/#downsides) so this isn't a recommended approach, and should be used as an escape hatch. - [Gatsby documentation on adding an image from the static folder](https://www.gatsbyjs.org/docs/recipes/#reference-an-image-from-the-static-folder)
lessonDuration 3m 8sFree
Nx is not only capable of scaffolding frontend projects, but it also supports a lot of backend setups. In this specific lesson, we're going to explore the setup we previously generated, specifically inspecting how passing `--frontentProject` to the Express.js schematic automatically sets up a [Webpack dev proxy](https://webpack.js.org/configuration/dev-server/#devserverproxy) to make it easy to call the backend API.