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

Getting Started with JSX in React

In this article we will take a look at the JSX⁠—an HTML-like syntax used by React to declare user interfaces. By the end of this post, you will have a better understanding of what JSX is, how it works, and why it's a preferred way to declare user interfaces in React.Let's start with an example: We start by importing React APIs from react and react-dom packages. We'll use these APIs later. Next, we declare the header React element. This will be an <h1> element. After that, we get the DOM node by its id. Finally, we ask React to render the header into the root DOM node with the ReactDom.render() function. We provide a React element to render and an HTML element that will be used as a container. The syntax we've used to declare the header is JSX—a special syntax used by React to declare UI. It intentionally looks like HTML to make it easier to work with UI elements and layout. As with HTML we can define attributes, which are called properties in React: Here we've got the same <h1> element with id and contentEditable properties defined. We can use strings and JavaScript expressions as values. In case of expressions, we wrap an expression with curly braces. Also, we can define children elements with JSX: Here we've got a <div> element that contains <h1> and <p> elements. If we'll try to run a code that uses JSX directly in a browser, we'd get an error message. This is because JSX is not a valid JavaScript syntax. We need to process this code first. We can use Babel or TypeScript for this. They will convert the JSX syntax into a plain JavaScript code. Let's take a look at the code before and after such conversion: Here we can see that our JSX declaration has been converted into the React.createElement() function call. This function takes three parameters. The first parameter defines a type of element to create, the second one is for properties, and the third one allows to specify children for the component. This function returns an object that is later used by React to render actual DOM nodes. As we've seen, JSX is a special syntax that got converted to React.createElement calls. So why use JSX instead of calling the createElement function directly ? To answer that, let's look at the following code: We can tell what happens here, but this requires reading through the code. Now, let's take a look at the same logic written with JSX: Here we can understand the structure after a glance. JSX is easy to read and reason about. That's the main feature of JSX that makes it preferable over the plain JavaScript. In this article, we've seen how to use JSX to declare React components. JSX makes it easier to declare your components and define UI of your application. It looks like HTML and got converted to pure JavaScript by Babel or TypeScript. When your React application runs in a browser, the browser knows nothing about JSX and works with JavaScript only. Here are additional resources that will help you to learn more about JSX and React:

Quick Introduction to Testing React Components with Enzyme

In this article we will see how to start using Enzyme for testing React components. We will add Enzyme to a React project and will write a test to make sure that our component works properly.Enzyme is a JavaScript testing utility that makes it easier to test React applications. It allows to simulate rendering of React components and ensure that the output and behavior of components are correct. Let's start by adding Enzyme to our project: We install the enzyme package and also the enzyme-adapter-react-16 adapter for the React 16 version that we're using for this article. Next, we need to configure Enzyme using the adapter. For a project created with Create React App we can use the global setup file to do that once for all tests. Otherwise, we would need to initialize the adapter manually. When using the Create React App project, we can create the src/setupTests.js file with the following content: Now we are ready to create our first test. Here's the solution that we are going to test: We've defined the MyComponent component that allows to enter a text. When a user submits text, the submit button gets disabled a thank you message is displayed. Now, let's create a simple test that will check that the component renders properly: In this test we start by importing the shallow function from Enzyme that performs the shallow rendering of a component. A shallow means that it will render a component but will skip rendering of children components. After that, in the Jest test function, we describe our test. We use the shallow function to get a wrapper object that represents a rendering result. Next, we use the wrapper object to check that the rendered component contains a welcome message and that a button is not disabled. Now let's test a case when a user inputs a text and submits data. We expect the component to disable a button and show a thank you message with the specified text: In this test we simulate the change event for the text input to set test text. After that, we simulate the click event on a button. Finally, we assert that the thank you message has been shown and that the submit button has been disabled. In this article, we've seen how to create simple tests for React components with Enzyme. There is much more possible with this testing library. You can learn more about Enzyme and writing great tests with additional links provided below. Here are additional resources that will help you to learn more about Enzyme and testing React components:

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

Introduction to React children Property and Building Better Components With It

In React we create new components using other components as building blocks. In this article, you will learn how we can build more reusable components with the children property.Seeing your React applications as a hierarchy of components is an important part of working with React. All components in React form parent-children relationships. For this article, you will need a basic understanding of how to use React components in your application to follow along. We'll be using JSX to declare our components as well. If you'd like to learn about components' hierarchy in React, check how to specify Children with JSX and Thinking in React guide. Let's start with an application that shows a dialog: We've got two components here: App and DialogMessage . The App component represents our application. It uses the DialogMessage to display a dialog. In the App component we use properties of the DialogMessage to define its title and a handler for a close event. We use state with useState() function to control the visibility of the dialog. The dialog contains three div elements for a header, content, and actions. Now, let's add another dialog message. This time, instead of a simple message we'd like to show a list of items. The straightforward way to do that would be to create a new component like this: Now we've got two similar dialog components. Both dialogs control their visibility in the same way. It is only the content that is different. In the DialogMessage we've got a text, and in the DialogList we've got a <ul> element with list items. The problem here is in the code duplication. If we'll go on adding dialogs this way, we'd need to create a new dialog component for every new type of message. This is time-consuming and we duplicate the code for the dialog logic even that it stays the same for all dialogs. What we'd like to have in our application may look like that: In this example, we've got a single Dialog component. We use it to show different types of content. We want to be able to wrap any content with our Dialog component. The same way as we use standard <div> element to wrap other components. Here's where the children property comes to the rescue. As we've seen, using JSX we define children for a component between its opening and closing tags. It turns out that React provides a special children property that gives access to children components of a component. This property is available for all React components. We can use this property to render children components. Here's how the implementation would look like for the Dialog component: In this example, we use the props.children in the Dialog component. We add children components into the content div element. We can use a single or multiple components as children, or leave the dialog empty. Now we have got a single implementation for our dialog. Using other components as children components is one of the key concepts in React. In this article, we've seen how we can build more reusable components using the children property. There are more advanced approaches that use this property. Links to them are available below. Here are additional links that will allow you to learn more about using the children property:

How to Start New React Application with Create React App and TypeScript

In this article you'll learn how to start a new React application with the Create React App that also supports TypeScript. We will look at the initial configuration of an application, and how to start adding new React components using TypeScript.To create a new React project with TypeScript support all we need is to run the following command: We provide the --template typescript parameter to specify that we need TypeScript support. Running this command will create a new React project. Let's take a look at differences between a project created by Create React App by default and the one with TypeScript support. The first thing you may notice is the tsconfig.json file at the root of a project. This file specifies settings that will be used by TypeScript when compiling our code. We can modify settings in this file if needed. Next, there is a new react-app-env.d.ts file in the src folder. This file references TypeScript types declarations that are specific to projects started with Create React App. These type declarations add support for importing resource files such as bmp, gif, jpeg, jpg, png, webp, and svg. That means that the following import will work as expected without errors: It also adds support for importing CSS Modules. This relates to import of files with .module.css , .module.scss , and .module.sass extensions. All JavaScript code files in the src folder will have TypeScript extensions. We'll have .ts extension instead of .js and .tsx instead of .jsx . Apart from the changes mentioned above, everything will work in the same way. You can use all the features of projects created with the Create React App. This includes eslint support, running tests, and development server with hot reload. Even the eject action will work allowing you to extract the configuration of the project if needed. After a project creation, we can start adding components to our application. Thanks to TypeScript support we can also declare types for our components. Here's an example of a functional component: We've specified the React.FC<IMyComponentProps> as a type for MyComponent . The React.FC type specifies that our function should return a React component or null. The interface specified as a generic parameter means that our component requires properties specified in the IMyComponentProps interface, which is message in our case. This allows TypeScript to check the returned value of our component function and also control the properties that we provide in code. In a similar way, we can add a class component: For the class component, we declare a class MyComponent . We derive it from the React.Component class that provides base functionality of a React's class component. The IMyContentProps interface allows to control properties, and the IMyComponentState interface controls the values we can put in the state. Create React App allows to quickly start a new React project with TypeScript support. The process is straightforward and does not require additional configuration. Here are additional resources that will give you more information about Create React App and TypeScript:

    You should start using Lodash in 2020 and here's why.

    In this article, we will learn about some of the most widely used programming tasks and implement them using Lodash functions. We'll learn: Lodash is Javascript library developed by John-David Dalton which focuses on delivering high-performing Javascript functions and more. Lodash can be used in the front end and in the back end as well. If you're ever in doubt whether you should use Lodash or not, ask yourself these questions: If you think that your answers to most of these question is a 'Yes' then you should use Lodash without a doubt! If you're not using any libraries or frameworks such as React, Vue, Angular or Node, the best way to install Lodash into your project is to include the following script in your root HTML file: You can now access Lodash using: If you want to use Lodash in libraries and frameworks such as React, Vue, Angular or Node, the first thing you need to do install Lodash via npm or yarn into your project by running the following command: You can have access to Lodash inside your React or Vue component by importing it directly from the Lodash library like so: To use Lodash in Angular, you need an extra package @types/lodash for type definitions Simply run this command from inside your Angular project: You can now access Lodash using: Lodash's official documentation suggests that we import Lodash in Node using the classic require syntax, so let's do it their way: Alright, we've now installed Lodash into our project, what's next? Mentioned below are few real world scenarios that I faced myself and how Lodash helped me in each one of them. Let's tackle them one by one. Let's say we have an object ( obj ) that we receive from an API endpoint (or anywhere else) and we would like to see if it is empty or not. With ECMA 7+ , we would do something like this: This gets even harder with Vanilla Javascript , we might have to write code that looks something like this: And if this returns true, only then we confirm that obj is an empty object, With Lodash , we could do that simply using: The isEmpty() function accepts one parameter: It returns true if obj is empty and false if it is not an empty object (or an array). How cool is that? The next case is where pretty much every developer must've stumbled upon at least once, which is: Let's say we have a book object which is received from an API endpoint like so: A situation might arise where we'd like to see if this book object has desc key in it or not. If it does have a desc key only then we show the description of the book inside our view. Here is how we do it using Lodash The has() function accepts two parameters: It returns true if book object has desc key in it, else it returns false. For the next case, let's say we receive an array of books from our API endpoint like so: Now, we'd like to get first book from this booksArray which has more than 150 pages (book Second). Using Lodash , we could simply do: The find() function accepts three parameters: It will return one book object i.e. as it has more than 150 pages and it is the first item in the booksArray that satisfies the pages > 150 condition. If we want all books that match the pages > 150 condition, then we could simply do: The filter() function accepts two parameters: It will return a new array like so: Now, let's talk a little bit about loops. How many time have you found yourself in a situation where you'd want to loop through a given array or an object? This raises the following question: Let's look at our original booksArray , we have 3 books in it and now we'd like to print them all one by one. Here is how we do it using Lodash: The forEach() function accepts 2 parameters: It will log all the three books one after the other to our console like so: Finally, have you ever come across letters like 'à' or 'é' . We know that these letters are similar to 'a' and 'e' (respectively) but they have this diacritical marks placed above them which is due to their Latin origin. Wouldn't it be great if we had a function that would remove these ugly marks from these letters and return their english counter parts for us? Lodash takes care of even this situation. The deburr() function accepts one parameter: It will return a new string removing diacritical marks like so: Lodash is a very popular Javascript library and has tons of other functions that come handy when working with array, objects, strings, numbers, etc. I want to talk about one last application of Lodash before we wrap this up. Though we have other more frequently used template engines like ejs, pug, etc, we are certainly not accustomed to use them. You can use Lodash as a template engine too. To install Lodash in your project, add this script in your html file: Now, let's say that we want to render our booksArray inside our html file. This is where we use: The template() function accepts two parameters: We have not used the Options object for the sake of simplicity. This will create 3 list items containing all 3 of our books like so: The complete code would look like this: Hope you enjoyed this tutorial! You can visit Lodash's official website to get an exhaustive list of Lodash's functions and more.