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

Server Side Rendering with React

In this article, we will learn how to render a simple React app using an express server.Server Side Rendering (SSR) can be a useful tool to improve your application's load time and optimise it for better discoverability by search engines. React provides full support for SSR via the react-dom/server module, and we can easily set up a Node.js based server to render our React app. In the following sections, we will create a simple counter app with React and render it server-side using an express backend. Let us use create-react-app to generate a stock React app. We'll call our app ssr-example . Let us modify the App.js file to implement a simple counter component that displays the current count. It will also render buttons with which the counter can be incremented and decremented. In our app's index.js file, we have the following line which tells React where to render our app. This needs to be slightly modified to work with SSR. To be able to render our app, we must first compile it so that an index.html and the compiled JavaScript is available. You can build the app with the following command: We will use express.js to set up a simple server for our app. You can install it using the following command in your project folder: Since the server needs to be able to render JSX, we will also need to add some babel dependencies. We will also install ignore-styles since we do not want to compile CSS. Let us create a server using the express module we have just installed. To start, create a folder called server in your project folder, and create a server.js file within it like so: We have just defined an express app that will listen on port 8000 when started. With the app.use() statement, we have also set up a handler for all requests to routes matching the ^/$ regular expression. In the next step, we will add code in the handler to render our app. But before we move on to that, we will need to configure our babel dependencies to work with the server we have just defined. To do so, create an index.js file in the server folder with the following code that imports the required dependencies, and calls @babel/register : Let us now add the code that actually renders our app. For this, we will use the fs module to access the file system and fetch the index.html file for our app. If there is an error reading the file, we will return a 500 status code with an error message. Otherwise, we can proceed with the rendering. The index.html has a placeholder element, usually a div with the ID root where it renders the React app. We will use the renderToString function from react-dom/server to render our App component as a string, and append it to the placeholder div . And that is pretty much it! We're now just one step away from being able to get this up and running. Let us add an ssr script to our package.json file to run the server. You can now start the server from your terminal with the command yarn ssr . When you navigate to http://localhost:8000 in your browser, you will see the app rendered as before. The only difference will be that the server responds back with the rendered HTML this time around. We have now learnt how to implement Server Side Rendering with a React app using a simple express server. The code used in this article is available at https://github.com/satansdeer/ssr-example , and a video version of this article can be found at https://www.youtube.com/watch?v=NwyQONeqRXA .

Thumbnail Image of Tutorial Server Side Rendering with React

    What is React’s useContext Hook and how do you use it?

    Hooks are small snippets of React power that allow you ‘hook’ into various parts of the React system, inside of function-based components. Hooks can target React features like state, element refs, or, in this case, context . Hooks were introduced into the React library in version 16.8 and they're designed to give developers access to parts of the React library that were traditionally reserved for class-based components. One such Hook that we're going to explore in this article is useContext , which gives our components the ability to access shared data from higher up parent components, without that data being passed through multiple layers of other components. In this article, you'll learn more about React's context concept, as well as how to define your own context object, store data inside of it, and access that data in child components using the useContext Hook. Context in React is defined very clearly in the official React documentation : By making various items of data available in a ‘global’ sense, context solves a familiar problem in React state management: prop drilling. Prop drilling is where you have a lot of components redundantly passing data down through layers of the component tree to child components, whilst not acting on (or requiring) that data at all. While this might not be a problem in a smaller scale app, as an app grows prop drilling can become unwieldy and hard to keep track of. Context allows us to easily share data between different components without prop drilling. To create and consume context, we need to follow these steps: Let’s walk through these steps to see how it works. Pretend that we have an app where we need to collect some user data from a server once they’ve logged in. We would likely do this in a top-level component, such as App.js . Once we have this data, we can make it accessible to any and all child components via context. So let’s create our App component and a user context object to stash our user data in. We can create a context object using the React.createContext() function. You can also import it from React as so, import { createContext } from ‘react’ . You pass it any default value that you want it to have. In our case, null is fine as it’ll make it easier to check if our user has any details. We need to export the context object here to be able to import it later down the component tree as you’ll see in a little while. However, that lonely Avatar component won’t be able to access the context unless we wrap it in a provider component. Let’s do that next. The next step in the process involves making our shiny new context object available to any and all child components down the line. To do this, we must wrap any child components (or next components in the tree) in a context provider component. In our case, we’ll wrap the Avatar component in the provider like this: The component name takes the form, NameOfContext.Provider . Since we created a context object called UserContext , to access the provider, we use UserContext.Provider . Notice that we’ve also passed the userDetails object into the value attribute? We’ve used a standard JavaScript object here, but you can pass primitives, or arrays, whatever you like really, into value . With that in place, our updated App component now looks like this. The only thing left is to grab the context value(s) from the provider in any child components using the useContext Hook. This is much simpler by comparison. In the Avatar component, that would look like this: Really simple, right?! Import the useContext Hook from React at the top of your component, then grab the context at this line, const userDetails = useContext(UserContext) , passing in the context object, UserContext we defined in the App file. From here, you can use any values from the context as you would. In our case, we might have access to a user’s name and profile image URL. Context is a great fit for some use cases, theming being one of them. Its primary purpose is to provide a means to share data between many components within a nesting structure. However, its use can be abused and you may be tempted to use context when some component refactoring (or component composition changes) could achieve the same result. Using context is fine, but it can make components less reusable as they’re more inherently tied to their context-providing parents, higher up the component chain. The official React documentation on context includes a great example of using component composition (i.e. how you create your components) over using context, and I’d recommend checking those out.

    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

    Testing a Create React App TypeScript Project with Jest and React Testing Library

    Building single-page React applications has never been easier. With a single command, Create React App (CRA) scaffolds an entire React application with development/build tools, such as Babel and Jest, automatically configured and integrated into the project. Getting started requires no additional configuration. Plus, it eliminates the need to maintain an entire build process, which can require lots of work and is very prone to error. However, the default template of Create React App does not include support for TypeScript, which has gained much traction in recent years. Below, I'm going to show you: To generate a new CRA project with TypeScript, provide the --template option to create-react-app and specify typescript as the template. Once the process is complete, view the project in an IDE (such as VSCode). Take note of the few differences between this template and the default template. Of course, TypeScript can be added to an existing CRA project by reproducing the above modifications. Replicating these steps on each new CRA project would be quite tedious and would waste valuable time that could be put towards designing/building your application. The CRA typescript template instantly did all this work for us. CRA templates simply offer conveniences that cannot be overlooked. Run the CRA application. You should see the following in your browser at localhost:3000 . Inside of src/App.test.tsx , there is a single unit test. ( src/App.test.tsx ) Run tests by executing the test NPM script: The test checks whether the "Learn React" link is rendered to the page. The React Testing Library ( @testing-library/react ) provides APIs for testing React components: Now, let's write several additional tests for the CRA TypeScript template project. To test if the React logo is rendered, use the getByAltText method, a semantic query method used for finding elements that support the alt attribute (such as <img /> ). This test should automatically pass. To test if the prompt to the user ("Edit src/App.tsx and save to reload") is rendered, use the getByText method. When you run the tests, you will notice that this test fails. This test fails because the query method encounters elements with parts of their text content wrapped in other elements such as <strong /> , <em /> , etc. Example : As the error message mentions, this issue can be resolved by passing a custom function as the text matcher argument to the getByText method. The function is executed on each node that's rendered to the page. When the function evaluates to true for a node, then that node will be returned as a matching node. On the contrary, when the function evaluates to false for a node, then that node will be ignored. This function accepts two arguments: Running the tests once more, all the tests pass. Experiment! Try out other queries and methods provided by the React Testing Library. The code for this post can found here . If you want to learn more about testing TypeScript + React with Jest and React Testing Library, then check out Fullstack React with TypeScript :

    Thumbnail Image of Tutorial Testing a Create React App TypeScript Project with Jest and React Testing Library

    Jest VSCode Plugin

    When writing tests for your application, it can be tedious and distracting to switch between the terminal and IDE to execute tests and verify that all tests are passing. What if there was a more streamlined approach that simply displayed the results of tests directly within the IDE, with each result (passing or failing) adjacent to its corresponding test? If you are writing tests using the Jest framework, and your IDE of choice is VSCode, then there is a plugin in the VSCode marketplace that automatically runs tests and shows individual test results inline. Getting this immediate feedback within the editor improves productivity and reduces context switching. Below, I'm going to show you: Click the "Extensions" icon in the Activity Bar on the left-side of the VSCode window and type "jest" into the search bar at the top of the Extensions view. Select the result with the publisher "Orta" (the first result with the most downloads). Install the plugin by clicking on the green "Install" button. When you open a project in VSCode with a Jest installation (detects Jest in node_modules ), this plugin will automatically start Jest. To demonstrate the capabilities of this plugin, we will explore how it runs for an existing project with Jest installed. Download this project from GitHub: Open the project in VSCode, navigate to the __tests__/index.test.ts file and open it. Take note of the checkmarks, which each indicate a passing test, preceding each it . If it doesn't show up automatically, then manually start the runner: To enable debugging for Jest tests, create a .vscode directory in the root of the project, and inside of this directory, add a launch.json configuration file that contains the following: ( .vscode/launch.json ) Here's what each configuration option does: In short, this configuration automatically launches and attaches the VSCode Node.js debugger to a process running the tests. Let's revisit __tests__/index.test.ts and make a small adjustment to one of the tests. For the first test, store the hex and RGB literals in an object, and reference their values from this object. ( __tests__/index.test.ts ) Place a breakpoint on the line with the assertion: Launch Command Palette ( CMD + SHIFT + p on Mac or CTRL + SHIFT + p on Windows). Select the option "Debug: Select and Start Debugging," followed by "Debug rgb-hex Tests." On the left, a debug pane with runtime variables, call stack and breakpoint sections will be shown. Notice how the values of the local variables (in this case, white ) can be observed. On the top, there will be control buttons that can be used to step through, restart or stop the execution of the tests. Since there are no more breakpoints, press the red square button in the control buttons group to stop the execution of the tests. Experiment! Add more tests and breakpoints. Explore VSCode's debugger's other features . If you want to learn more about testing TypeScript + React applications with Jest, then check out Fullstack React with TypeScript :

    Thumbnail Image of Tutorial Jest VSCode Plugin

    Testing TypeScript Code with Jest

    Jest is an open-source, JavaScript testing framework maintained by Facebook. With an exceptionally large assertion library and a simple, well-documented API , writing tests for JavaScript code with Jest is easy and requires no additional configuration. For TypeScript code (and JavaScript code that needs to be transcompiled with Babel), you will need to install a few extra NPM packages and provide a small Babel configuration. This process is not difficult and takes little time to complete. By setting up TypeScript and Jest in the early stages of your project, this upfront investment will pay exponential dividends in the latter stages of your project. Below, I'm going to show you: Pairing TypeScript and Jest creates layers of code quality assurance for any project. With TypeScript, static type-checking can immediately catch many common mistakes such as invalid arguments being passed to a function, etc. Adding type annotations not only enforces type checking, but also serves as a form of documentation. Editors with intelligent code completion are able to instantly notify the developer of potential bugs in their code. VSCode Intellisense (JavaScript) : VSCode Intellisense (TypeScript) : With Jest, a robust test suite can be written with little boilerplate code. Plus, developers are able to confidently refactor or add features to an application without having to worry about introducing new unexpected bugs or regressions to other parts of the application. The combination of TypeScript and Jest ultimately leads to long-term maintainability. To demonstrate how quick it is integrate Jest into a TypeScript project, we will add Jest to a small Node.js library built with TypeScript. Download this project from GitHub: Note : The "master" branch hosts the library with Jest. If you find yourself lost during the walkthrough, then feel free to refer to the code in the "master" branch. Install Jest as a dev. dependency. Because Jest supports TypeScript via Babel, install @babel/plugin-transform-typescript , a plugin that adds support for the TypeScript syntax, as a dev. dependency. To use import statements in Jest test files (and support the latest, commonly-used JavaScript features), install @babel/preset-env as a dev. dependency. A single preset conveniently contains an array of Babel plugins. This eliminates the need to manually install individual Babel plugins for standard JavaScript features that you would expect out-of-the-box support for such as @babel/plugin-transform-arrow-functions for arrow functions and @babel/plugin-transform-spread for the spread operator. Add a babel.config.js file to the root of the project to configure Babel with these presets. Set the target environment of @babel/preset-env to the current version of Node that you are running, which allows Babel to only transpile features that are not natively supported by the specified environment. ( babel.config.js ) This library provides two simple methods for converting color values, rgbToHex and hexToRgb : Let's add several unit tests for each method. In the root of the project, create a __tests__ directory. Inside of that directory, create a new file named index.test.ts . Inside of index.test.ts , define two top-level describe blocks to encapsulate all the unit tests. Each block will group together unit tests related to one of the methods. ( __tests__/index.test.js ) Next, at the top of the index.test.ts file, import the methods rgbToHex and hexToRgb . ( __tests__/index.test.js ) Inside the body of the first describe block (housing rgbToHex tests), let's write some simple tests. Each it block represents a single test (also called spec), and inside of each test is an assertion. ( __tests__/index.test.js ) To test the code, add the following NPM script to package.json and execute it. ( package.json ) All the tests should pass with flying colors! Now let's test the remaining method hexToRgb . Inside the body of the second describe block (housing hexToRgb tests), let's write some simple tests. ( __tests__/index.test.js ) When you run the tests, all the tests should pass with flying colors! If you happen to forget what kind of arguments need to be passed to a method, or need to be reminded of what the method does via a documentation comment (JSDoc/TSDoc), then hover over the method name and Intellisense will display a tooltip with the full function signature (with type annotations) and along with the comment. Experiment! Visit the Jest documentation and add more tests using some of the other matcher functions. If you want to learn more about testing TypeScript with Jest, then check out Fullstack React with TypeScript :

    Thumbnail Image of Tutorial Testing TypeScript Code with Jest