Latest Tutorials

Learn about the latest technologies from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

    Cyber Monday Starts Now! 🎉

    Our biggest discounts and best sale of the year continues through Cyber Monday! We're offering discounts in four ways: These discounts are available for a limited time only - and our discounts will never be lower, so this is your chance for our best offer. Use the coupon links below for these exclusive discounts! Get 1 month of newline PRO  free when you purchase a yearly subscription. With newline PRO you get access to over 500 lessons, thousands of pages, across all of our books and courses. You get full access to our best-sellers like Fullstack D3 , Fullstack React with TypeScript, Fullstack Vue and tons more.  You also get Early Access to new Guides like: The newline Guide to React Component Design Systems with Figmagic, Fullstack Web Components  and The newline Guide to Storybook for Building React Apps.  We have 30+ new Guides scheduled for release next year that go in-depth into the wide range of things you have to know as a developer in 2022. Get your yearly newline PRO subscription with 1 month FREE  discount here

    Thumbnail Image of Tutorial Cyber Monday Starts Now! 🎉

      Black Friday 2021 Sale! 

      It's Black Friday and to celebrate we have our biggest discounts of the year today. We're offering discounts in four ways: These discounts are available for this weekend only - and our discounts will never be lower, so this is your chance for our best offer. Use the coupon links below for these exclusive Black Friday 2021 discounts! Get 1 month of newline PRO  free with a yearly subscription. With newline PRO you get access to over 500 lessons, thousands of pages, across all of our books and courses. You get full access to our best-sellers like Fullstack D3 , Fullstack React with TypeScript, Fullstack Vue and tons more. You also get Early Access to new Guides like: The newline Guide to React Component Design Systems with Figmagic, Fullstack Web Components  and The newline Guide to Storybook for Building React Apps.  We have 30+ new Guides scheduled this year that go in-depth into the wide range of things you have to know as a developer in 2022. Get your yearly newline PRO subscription with 1 month FREE  discount here

      Thumbnail Image of Tutorial Black Friday 2021 Sale! 

      I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

      This has been a really good investment!

      Advance your career with newline Pro.

      Only $30 per month for unlimited access to over 60+ books, guides and courses!

      Learn More

      Annotating React Styled Components with TypeScript

      Styled components redefine how we apply CSS styles to React components. Unlike the traditional approach of manually assigning CSS classes (from an imported CSS file) to elements within a component, CSS-in-JS libraries like styled-components provide primitives for locally scoping CSS styles to a component with unique, auto-generated CSS classes. Consider a simple <Card /> component composed of several styled React components. Each of styled 's helper methods corresponds to a specific DOM node: Here, the <Card /> component's styles, structure and logic can all be found within a single file. styled-components comes up with a unique class name for each set of CSS rules, feeds the CSS to a CSS preprocessor (Stylis), places the compiled CSS within a <style /> tag, injects the <style /> tag into the page and adds the CSS classes to the elements. By tightly coupling components to their styles, we can easily maintain CSS in large React applications. If we need to edit anything about a component, whether it be its color or how it responds to user input, then we can visit one file, which keeps everything related to the component colocated, to make the necessary changes. Unique class names prevent naming collisions with existing class names. Popular CSS-in-JS libraries, such as styled-components and Emotion , come with TypeScript definitions. When pairing styled components with TypeScript, our React application gains all the benefits of a statically typed language while also ensuring component styles remain well-organized. As we write our styled components, our IDE can warn us of any incorrect arguments passed to any of the helper methods, detect typos, perform autocompletion, highlight missing props, etc. Below, I'm going to show you how to annotate React styled components with TypeScript. To get started, scaffold a new React application with the Create React App and TypeScript boilerplate template. Within this new project, install the styled-components library and @types/styled-components , which provides type definitions for styled-components . Within the src directory, create a new directory, components , which contains the React application's components. Within this new directory, create a new file Card.tsx , which contains a <Card /> component. Copy and paste the <Card /> component's source code (from above) into this file. For React Native projects, you would need to install an additional set of type definitions: Then, you must add styled-components-react-native to the list of types in tsconfig.json : ( tsconfig.json ) Suppose we wanted to annotate the example <Card /> component previously mentioned. Annotating a React functional component requires: ( src/components/Card.tsx ) If we want to add to or override the <Card /> component's styles within a parent component, then we need the <Card /> component to accept an optional className prop. By default, all properties are required, but those marked with a question mark are considered optional. ( src/components/Card.tsx ) Now the <Card /> component can be modified from a parent component. ( src/App.tsx ) Suppose a styled component's inner DOM element must be accessed by a parent component. To forward a ref to a styled component, we must pass the styled component to the forwardRef function, which forwards the ref to an inner DOM element that the styled component renders. Annotating a styled component that receives a forwarded ref involves two steps: ( src/components/Card.tsx ) The parent <App /> can obtain a ref to the underlying <div /> element and access it whenever it needs to register event listeners on the component, read/edit DOM properties, etc. ( src/App.tsx ) styled-components lets you easily customize your React application's theme via the <ThemeProvider /> wrapper component, which uses the context API to allow all children components underneath it to have access to the current theme. ( index.tsx ) When adapting styles based on props, TypeScript automatically recognizes the theme property on the props object. Below is a screenshot of passing a function to a styled component's template literal to adapt its styles based on its props. Notice that TypeScript raises no warnings or errors when you reference the props object's theme property. In fact, if you happen to use VSCode and hover over props , then a tooltip with its type definition appears. If you hover over props.theme , then you will see its type definition ThemeProps<any>.theme: any . The any indicates that TypeScript will not raise any warnings no matter what property you try to access from props.theme , even if it does not exist! If I reference a property on the props.theme object that might reasonably be available on it like primary , or something ridiculous like helloWorld , then TypeScript will not raise any warnings for either. Hover over any one of these properties, and a tooltip with the type any appears. By default, all properties on the props.theme object are annotated with the type any . To enforce types on the props.theme object, you must augment styled-components 's DefaultTheme interface, which is used as the interface of props.theme . For now, start by defining the primary property's type as a string (i.e., we might set the primary color of the default theme to red ) in DefaultTheme . ( styled.d.ts ) Note : By default, DefaultTheme is empty . That's why all the properties on the props.theme object are annotated with the type any . Within tsconfig.json , add the newly created styled.d.ts declaration file to the list of included files/directories required by TypeScript to compile the project: ( tsconfig.json ) Now, if you revisit the Card styled component, then you will see TypeScript raising a warning about props.theme.helloWorld since we did not define its type within the DefaultTheme interface. If you hover over props.theme.primary , then a tooltip with its type definition, DefaultTheme.primary: string , appears. Plus, if you revisit the index.tsx file, then you will also find TypeScript warning about the theme object being passed to the <ThemeProvider /> wrapper component: This issue can be resolved by replacing the main property with the primary field: Better yet, you can import DefaultTheme from styled-components and annotate the object with this interface. Back inside Card.tsx , you can refactor the Card styled component by setting background-color directly to the current theme's primary color. To see the final result, visit this CodeSandbox demo: https://codesandbox.io/embed/keen-satoshi-fxcir?fontsize=14&hidenavigation=1&theme=dark Try annotating styled components in your own React applications with TypeScript.

      Thumbnail Image of Tutorial Annotating React Styled Components with TypeScript

        Continuous Integration with GitHub Actions

        Efficient developers implement CI/CD pipelines to automate all sorts of tasks: Cloud-based CI/CD services, such as Travis CI and CircleCI , simplify the complex process of automating builds, testing and deployments. Developers define the build environment (e.g., programming language, type and version of runtime engine and operating system) and tasks to execute all within a single configuration file, often formatted using YAML. For Travis CI, there's .travis.yml , and for CircleCI, there's .circleci/config.yml . The configuration file guides the CI/CD service as it provisions virtual machines with the proper environment and runs tasks sequentially and/or in parallel upon triggering certain repository events. Depending on the event, you may specify a unique workflow that runs its own set of tasks. For example, merging code to the production branch automatically tells the CI/CD service to spin up a new isolated virtual machine and kick off a workflow that builds and deploys your application. Another common event is creating a pull request. This event also automatically tells the CI/CD service to spin up a new isolated virtual machine. However, it may kick off a workflow that lints and tests code and generates a code coverage report. Workflows can be customized to streamline whatever tedious tasks you (and your collaborators) may forget to run. To remain productive while shipping code with confidence, you should add as many of these tasks to a CI/CD pipeline so that you can focus more on the application code. If you already have your project hosted on GitHub, then you should consider automating the project's workflow with GitHub Actions , GitHub's CI/CD solution. Choosing GitHub Actions over Travis CI or CircleCI gives you one less third-party service to worry about and store your GitHub token. Despite being launched in late 2018 , GitHub Actions' free tier for open-source software (and monthly credits for private repositories) rivals the plans offered by other well-established services. Plus, being natively integrated with GitHub lets you automate issue triaging, hook into any GitHub event and connect with other GitHub platforms and tools like GitHub Packages . For those who want to programmatically interact with GitHub Actions, the GitHub Actions API provides access to GitHub Actions via a REST API. Below, I'm going to show you how to set up and run a workflow with GitHub Actions. In this tutorial, we will write an automated workflow for a small utility library . The library converts a color from its hexadecimal representation to its RGB representation and vice-versa. When a contributor creates a new pull request, the workflow should... This way, we can check if the changes made in a new pull request unintentionally introduce bugs that break existing functionality even if the submitter forgets to lint and test their changes. To begin, clone this library to your local machine: Within the library's directory, delete the .git directory so that you can create your own GitHub repository to try out GitHub Actions. To enable a workflow for the library's GitHub repository, create a .github/workflows directory at the root of the library's directory and create a pull-request.yml file within it. Inside of the .github/workflows/pull-request.yml , let's name the workflow "Pull Request." ( .github/workflows/pull-request.yml ) We want GitHub to trigger this workflow whenever a pull request: Essentially, we want to lint and test the code whenever we make any changes to it. Using the on workflow syntax, we can define which GitHub event/s trigger the workflow. Events range from repository events (e.g., creating a pull request) to workflow events (e.g., after a workflow has completed). To run a workflow anytime a pull request event occurs, nest pull_request under on , like so: ( .github/workflows/pull-request.yml ) Under pull_request , nest types to specify the types of pull request events to trigger on and branches to narrow the pull requests to listen for events on by target branch. The workflow should run for pull requests with a target branch of main and that have been created ( created ), reopened ( reopened ) or received a commit ( synchronize ). ( .github/workflows/pull-request.yml ) The workflow will run one job named pull-request (ID of the job). This job runs on a fresh virtual machine with the latest Ubuntu operating system installed. ( .github/workflows/pull-request.yml ) The pull-request job consists of several steps. The first step is to checkout the code with the checkout action , like so: ( .github/workflows/pull-request.yml ) This lets the workflow access your repository. Then, the job must install the latest LTS version of Node.js (16.x) on the virtual machine with the setup-node action , like so: ( .github/workflows/pull-request.yml ) Replace @GITHUBUSERNAME with your own GitHub username (must include the @ prefix). Once installed, the job installs the library's npm dependencies via the npm ci command , which works similarly to npm install , but is used in CI/CD environments to ensure a clean installation of the dependencies. ( .github/workflows/pull-request.yml ) Notice that the uses syntax applies to GitHub actions and the run syntax applies to single commands. With the environment prepared, the job lints and tests the library's code, like so: ( .github/workflows/pull-request.yml ) Finally, the job uses the Jest Coverage Report action to generate a comment within the pull request that tabulates the statements, branches, functions and lines covered by tests. ( .github/workflows/pull-request.yml ) The action must be provided an action parameter of github-token to have permission to the repository. Altogether... ( .github/workflows/pull-request.yml ) When you initialize a new GitHub repository and try to push the library to a new remote GitHub repository, you may run into the following error message: This means your personal access token does not include the workflow scope. You should visit your GitHub tokens , select your personal access token (the one currently stored on your local machine) and check the workflow checkbox under the list of available scopes: Note : If you have not set up a personal access token, then please set one up by following the directions in the official documentation here . Now push to the main branch of the remote GitHub repository. Under the "Actions" tab of the library's GitHub repository page, you will find the "Pull Request" workflow listed under "Workflows." Suppose you add a new function to the library and decide to create a new pull request to have it reviewed before being merged to the main branch. Once the pull request is created, GitHub triggers the "Pull Request" workflow. Click "Details" to view the logs of the job as it's in progress. Once the job finishes, revisit the pull request. You will notice that the checks have passed and a code coverage report has been generated by the Jest Coverage Report action . Workflow jobs in GitHub Actions can be composed from smaller actions. Visit GitHub's marketplace here to explore the many open-source actions that can be integrated into your CI/CD pipeline. Try out GitHub Actions on your next project!

        Thumbnail Image of Tutorial Continuous Integration with GitHub Actions

          Design Systems for React Applications with Ant Design

          Material Design by Google . Fluent UI by Microsoft . These design systems enforce design patterns and rules that bring brand consistency to their companies' many products. When different products draw upon the same design system, they are bound to the same set of design principles and feel connected. Anyone who has used Google Docs and/or Google Sheets can easily tell that they are affiliated with Google just by looking at the colors, components, typography, etc. used by them. If you only knew how to use these products, then learning another one of Google's many products, such as Google Slides, would take much less time. Since there will be interactions and elements that you may recognize from before, your experience with the new product already begins with some level of familiarity. This lets you navigate the controls and learn new functionality and tricks with greater ease. Companies like Google and Microsoft have poured many resources developing these design systems. Yet, having these design systems at their disposal has allowed them to quickly create prototypes for new ideas and turn them into products that can be added to their ever-growing suite of products. Building a comprehensive design system requires developers and designers to work together to implement a set of reusable components that can be applied in current and future products. Anytime a team starts a new project, they can reach for this toolbox of pre-made components and preselected colors, typography, etc. and deliver the same aesthetic and user experience. A great (and effective) design system: If you (and your team) cannot afford to allocate development time towards building your own design system from scratch, then you should consider a customizable, well-documented design system like Ant Design. With over 70,000 stars on GitHub and adopted by large companies like Alibaba and Tencent, Ant Design (AntD) was designed to handle the complex design problems often encountered in enterprise-level products. It offers an extensive React component library (written in TypeScript) that supports: Its emphasis on several design principles forms a solid design foundation that anyone can build upon: Below, I'm going to show you: To get started, scaffold a new React application with the Create React App and TypeScript boilerplate template. Inside of this project's root directory, install the antd dependency: Delete the contents of the src/App.css file. Import Ant Design's styles at the top of this file, like so: ( src/App.css ) Import the <DatePicker /> component from antd and add it to the <App /> component. The <DatePicker /> component is an input field that, when clicked on, pops open a calendar widget for selecting a date. Note : If you come across the error Could not find a declaration file for module 'react/jsx-runtime'. , then bump up the version of @types/react from ^17.0.0 to ^17.0.3 . Run the application and visit it within a browser at localhost:3000 : Each time you pick a date from the calendar popup, the date's Moment object and its formatted string gets printed to the developer console. If you want to replace Moment.js with a lightweight date library like date-fns , then create a custom <DatePicker /> component that's configured with this library. Create a new file named DatePicker.tsx within the src directory. Then, import the dateFnsGenerateConfig object from the library rc-picker/lib/generate/dateFns and generatePicker function from the library antd/es/date-picker/generatePicker . dateFnsGenerateConfig is a version of the <DatePicker /> component's configuration with methods that all manipulate dates using date-fns . We pass this configuration object to generatePicker function, which returns a <DatePicker /> component configured based on this object. ( src/DatePicker.tsx ) Inside of src/App.tsx , substitute the import statement... With... Rerun the application. Notice how the developer console prints a plain JavaScript date, not a Moment.js object, whenever you click on a date within the calendar popup. Best of all, there are plenty of other components (e.g., widgets, layouts, etc.) available for use. Visit the "Components Overview" page of the Ant Design documentation site here for a list of all the components and information on how to use them. To customize the default Ant Design theme, you will need to override the Create React App project's Webpack configuration. Instead of ejecting the application, we can install the craco library, which lets you do everything react-scripts does, but taking into account modifications made to the Create React App project's Webpack configuration via a craco.config.js file: Note : CRACO is an abbreviation for "Create React App Configuration Override." Update the package.json npm scripts start , build and test with craco in place of react-scripts , like so: ( package.json ) Within the root of the project directory, add a craco.config.js file. ( craco.config.js ) Since Ant Design's styles are written in Less, you only need to change the value of LESS variables to change the theme's colors, typography, etc. Rename the src/App.css file to src/App.less . Within this file, import the Less file, not the CSS file, of the Ant Design styles. ( src/App.less ) Within the src/App.tsx file, import this Less file. ( src/App.tsx ) Install the craco-less package, which is a craco plugin that provides Less support for Create React App applications: Configure CRACO with this plugin. Using this plugin, modify the @primary-color Less variable to red . The modifyVars option tells the plugin to modify the values of the specified Less variables. Rerun the application. You will see that the primary color is no longer #1890ff , but is now red . This tutorial only scratches the surface of what's capable with Ant Design. Try customizing Ant Design to fulfill your own React application's needs.

          Thumbnail Image of Tutorial Design Systems for React Applications with Ant Design