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

Quick Introduction to Styling React Components with Emotion

In this article, we will see how to style React components with Emotion. We will learn how to add, configure, and use Emotion in React applications.We can define styling for our React components directly in the JavaScript code without using CSS files. This is a great way to apply dynamic styling and to compose multiple styles together. In React, we can use inline styling using the style property that is available for all components. There are drawbacks to this approach though. It is hard to compose inline styles, nested selectors and media queries are not supported, there is no auto-prefixing, and no theming support. Emotion is a library that helps to write CSS styles in JavaScript. It combines the advantages of inline styling with the power of CSS files. Emotion allows us to define dynamic styling, supports styles composition and themes. It also integrates nicely with React which makes Emotion a good choice for styling in React applications, especially when building reusable components. For this article, we assume that you're familiar with React components basics, such as working with component's properties. Let's start by adding Emotion to a project. There are several ways you can use Emotion in React projects. We'll be using the styled function to apply styling to React elements. This approach works well with React and does not require additional configuration. There is also the css property . It integrates with React components but requires additional Babel configuration. This makes it difficult to use in projects based on Create React App as CRA does not support custom Babel configurations. We can use the css property in small projects and projects where you can modify Babel configuration. It is also possible to use emotion in projects without React. You may check out the documentation for the emotion package for additional guidance. We need to add two packages to use Emotion with React: Now, we can use Emotion to apply styling to React components: We use styled to create a React component with custom styling applied to it. We can call styled by specifying the name of an element or a React component. For standard elements, the function also provides handy utility functions. For example, the following calls are the same. Both will return a new React component that will render a button with custom background color: We also provide the string with CSS properties to apply, just as in CSS files. The function returns the StyledButton React component. This is the component based on the button element with additional styles applied. Finally, we use the StyledButton component to render a button with our custom styling. There are two ways to declare styles with the styled function. In our example, we use a tagged template literal . We could also use an object with the inline styling naming rules . The following declarations are identical and you can select the one you prefer: With Emotion, we can use media queries, nested and pseudo selectors. CSS rules will be automatically auto-prefixed as well. We can have the dynamic configuration of the inline styling and power of CSS selectors at the same time. For example, let's declare a custom button component with nested selectors and dynamic configuration: In this example, we have got a more complex button component. We're using the :hover pseudo-selector to add styles for hovering. There's also the media query defined that makes the font-size larger on big screens. The StyledComponent also contains the <span> element with text. We're using the nested CSS rule for span to define the font-family and color properties. The value of the color property comes from props that can be passed to the StyledComponent . We use this property while rendering to create two buttons with different text colors. Emotion is a library for styling React components with JavaScript. We can declare powerful React components with dynamic styling and complex CSS rules. In this article, we gave a quick overview of the Emotion library. There are more features that we haven't covered in this article. We encourage you to learn more about the Emotion and start using it in your React projects.

Thumbnail Image of Tutorial Quick Introduction to Styling React Components with Emotion

How to Render Markdown in React with react-markdown

In this article, you will learn how to use Markdown in React applications using the react-markdown library. We will see how to render and control the look and feel of your Markdown markup.Markdown is a lightweight markup language that is easy to learn and work with. It is platform-independent, easier than HTML, and supported by lots of web and desktop applications. It is a great choice for content in React applications that changes once in a while. For example, FAQ, about, and help pages. The Markdown content can be easily managed by non-tech-savvy users. You can use Markdown instead of HTML or rich-text editing for user-generated content. React-markdown is a library that provides the React component to render the Markdown markup. We will use this library to render our Markdown. For this article, we assume that you already know the basics of Markdown. We also assume that you're familiar with React components basics, such as working with component's properties. Let's start by adding the react-markdown to a project: The react-markdown library provides the ReactMarkdown component we can use to render Markdown. Now, let's render some Markdown markup: We start by importing the ReactMarkdown component. Next, we declare Markdown content in the markdown variable. Finally, we render the ReactMarkdown component. We provide the content to render with the source property. You may notice that the HTML <b> tag renders as plain text in our example. This is important especially if we allow users to generate content. By not parsing HTML we prevent security issues related to cross-site scripting attacks. We can also change this behavior for trusted environments. We can use custom React components to change the behavior of rendered elements. For each supported node type, we can specify a React component using the renderers property. Our components will override default rendering. For example, let's specify a custom component for images. We will allow users to click on an image to make it larger: We've declared the MyImage component. It renders an image and handles the onClick event. Depending on the state fullSize variable we apply either large or small CSS class name to an image. We provide a custom rendering component to the ReactMarkdown component with the renderers property. It accepts an object, keys of the object are names of nodes and values are custom React components to use. We've defined that for the image node ReactMarkdown should use our MyImage component. React-markdown provides the ReactMarkdown component we can use to render Markdown markup. It ensures that the markup rendered is safe to use and provides a lot of configuration options.

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

Axios JS & Node.js a match made in heaven for API consumption

Axios is a popular JavaScript HTTP client, in this post we will go through some of the most common use cases with Node.Let's explore Axios JS and its usage cases with Node While building a Node.js application or microservice is pretty common you might end up needing to consume a third-party API, or just doing HTTP calls in general, and if that's the case Axios got you covered. Axios provides us an elegant and modern way to handle HTTP requests from Node using promises, to avoid old practices like having to rely on callbacks or deprecated modules such as Request . The pros of using Axios are: If you have ever used before Node.js you are good to go, this is an entry-level article, but here are some interesting articles that might enhance your grasp on the subject. Axios is available through most of the major Node package registry Using npm: Using yarn: To import Axios in our node app we do: Lets now use the library to do our first HTTP GET request, also to take advantage of Axios native promises using await we will abstract it using an async function: jsonPlaceholder is a fun little toy API server, which is great for this exercise, the resulting response object will be something like this, lets put our emphasis in the data property, which contains the response data sent by the server: The functions axios.post(url, data , options) , axios.put(url, data, options ) and axios.delete(url) Often you will have the need to set custom request headers, or setting a custom request timeout, we can achieve this through the Axios request config option To properly check for the Axios errors, to get the most amount of information, we need to check in the proper order: In the following code we showcase the proper way to filter through these cases, using a catch block: The first one we are going to showcase is, axios-retry , and as its name states is a retry plugin for Axios, let us retry failed requests, and set retry conditions and timeouts for these requests: To install axios-retry using NPM we do Last but not least, let's try out the Axios mock adapter To install axios-mock-adapter using NPM we do: Axios mock adapter allows us to easily create a mock server and attach it to our Axios instance, this is ideal for a controlled testing environment where you want to black-box your application We've been through a lot, within this short post, but with these tools, you should be able to do the basic HTTP operations with Axios. Have fun doing HTTP requests to an API, or crawling a website (while being responsible!) or just pinging your services through to know if they are alive. Have fun and keep coding! Check out the documentation of the modules we used in this post: If you have any questions - or want feedback on your post - come join our community Discord . See you there!

Angular Routing Explained

In this article, we will explore the different features of the Angular router and learn how to use it to build routing for various use cases.Photo by Joseph Barrientos on Unsplash Routing is one of the most important concepts when it comes to building modern Single Page Applications . It is also one of the most complex topics to understand. To put it in context, let us take a little trip back in time. πŸ•° Earlier generations of web apps usually had multiple HTML pages, connected together using hyperlinks. Whenever the user clicked on a link, they were navigated to a new page and the whole screen was redrawn. This was also the case with applications that used forms - the page was refreshed each time a form was submitted. βŒ›οΈ In subsequent generations, approaches such as AJAX became available. It became possible to make HTTP requests using JavaScript and update parts of the screen without having to redraw the entire page each time. This led to the rise of libraries such as jQuery , and eventually to modern, present-day web frameworks such as Angular and React . These frameworks are used to build Single Page Apps, which, like their name suggests, only have a single HTML page. However, they use a component called a Router to simulate the behaviour of multi-page apps. In the upcoming sections, we will dive into how the Angular Router works and the various features it offers. Before diving into the details of how to work with the Angular Router, it's worth understanding how it actually works. Like any single page app, an Angular app has a single index.html file in which the entire app is loaded. The entry point for the app is usually the AppComponent . When Angular bootstraps the app, the AppComponent is loaded into view. The AppComponent 's template is generally used to render parts of the app that always remain on screen, such as a header bar etc. This template will also include a <router-outlet> tag. This is a special tag which Angular uses to render views that are associated with the current route. For example, if you have a /home route, and you have set it up to show the HomeComponent , the router outlet will render the HomeComponent when a user navigates to yourapp/home in their browser. The router can also be used to render multiple routes at once. This is done by having multiple router outlets, each with its own unique name. This can be useful, for instance, if you want to have a sidebar that needs to appear when the user clicks a button but has to stay on screen even after the user has navigated away. You can either create a new project using the Angular CLI or use an existing project that you have. If you're creating a new project, make sure to add routing to the project while creating it with the CLI. Any new CLI project that includes routing will have an AppRoutingModule . This is the top-level routing module, where you can specify the routes in your application. In essence, it is the same as any other NgModule . The only difference is that it imports Angular's RouterModule by invoking the forRoot static method with the defined routes array. Any routes you would like to add into your app can be specified in the array passed to the RouterModule . These routes can be specified in a few different ways. This is the simplest way of defining a route. It indicates that the HomeComponent is loaded into view whenever a user navigates to the /home route in your app. A route can also specify a redirect to another route. This is useful when you don't have a component that's loaded on your default(empty) route and need to direct users to a certain page when they hit your app. When specifying redirects, a pathMatch strategy needs to be specified. A pathMatch value of full will match the path against the full URL, whereas prefix , which is the default strategy, will stop when it finds the first match. When redirecting from the default route, pathMatch: 'full' should be used, since the empty route will always result in a match when using prefix . Route paths can also specify a wildcard. This path will get navigated to if the router is unable to find another match from all the other routes specified. A route can have other routes nested inside it via the children property. In this example, the SettingsComponent will be rendered when the user navigates to /home/settings in the browser. Additionally, routes can also take an optional data property that can specify any value that needs to be passed into the component on that route. A common use case for most applications is dynamic routes - this means a URL that is generated on the fly using a resource ID or name - for example, /people/bob , or /projects/3 . In this section, we will learn how to configure routes to handle this scenario. This route has a :name token which represents a person's name. When a user navigates to /people/bob in the app, the router recognises it as a match with this route, and loads the PersonComponent . The :name parameter is made available in the PersonComponent via the injectable ActivatedRoute service. The ActivatedRoute exposes a paramMap observable which contains the value of the name parameter. In the following example, we get the value of the parameter and invoke a service to fetch the person's details. Apart from specifying them in your routing module, there are two ways to navigate between routes in your application. The Angular Router provides a routerLink directive for use in templates. Think of this as a special type of hyperlink, or <a> tag, which links to a route inside your application. This is the simplest usage of the routerLink directive, which just links to the /home route. It also takes a routerLinkActive property which can be used to provide a CSS class that will be applied when the link is active. When you have a dynamic route that depends on a parameter being passed, in you can use the routerLink like so: In this case, we will need to bind the value to the routerLink using a property binding, as it uses a value from your component. The value passed into the routerLink is an array of 'route link parameters' containing two items: In case you have multiple router outlets in your app, you can also specify the particular one in which your route needs to be loaded. The value here is slightly different - it is an object containing the key outlets . This outlets property is a key-value pair. Like many features of Angular, the router is also built using RxJS. It exposes an observable interface for listening to various events that occur during routing. In your app, you can subscribe to these events and execute custom logic in certain scenarios. Angular Router provides a number of Router Events that can be listened to. However, the most commonly used ones are those relating to navigation, such as NavigationEnd and NavigationError . Let us look at a practical example to understand better how to use Router Events. A common bugbear with single-page apps is that since they only have a single HTML file, they are harder to optimise for search engines. One of the reasons for this is that the page title remains static while navigating between routes in your application. This makes it more difficult for search engines to index. We can use Router Events to dynamically change the page titles when navigating between routes. To listen to these events, you can inject the Router into your component's constructor, and use the following code. Since this.router.events is an Observable , you can apply any RxJS operator to transform it according to your need. In this case, we are filtering out any other events and listening only to NavigationEnd events. As we discovered earlier, we can pass in a title value as part of the route data. We can access by injecting ActivatedRoute into your component and mapping the above Observable to it. Now, the only remaining part is to set the title of the page. Fortunately, Angular provides a Title service in the @angular/platform-browser package, which does exactly what we need. Another common use case for applications is guarded routes - there may be routes in your app that you only want authenticated users to access, for example. Angular has the concept of Guards, which provide a means to block navigation to a route if a certain condition is not met. Guards are classes that implement one of two interfaces - CanActivate - for guarding access to a route - or CanDeactivate - for guarding access from a route to another route. A CanActivate guard is typically used to shield authenticated routes. This can then be added onto a route as follows: A resolver can be used to pre-fetch data that a certain route may need before getting loaded. An example of this is when navigating into a 'page' that represents a resource, such as /projects/3 , we would like to use the ID 3 to fetch the project data from the store so it can be visualised on that page. Resolvers implement the Resolve<T> interface which has a single resolve method. This method returns either an Observable or Promise of type T . A resolver to fetch project data will look like this: The Angular router provides a means of splitting up code into chunks so that the initial load time of the app is cut down to a minimum. Chunks that are not necessary to render the landing page are then loaded subsequently when the user navigates to the respective routes. Previously, we saw how we can specify nested routes using the children property. The code associated with routes that are children of a particular route only needs to be loaded when the user navigates to that route, as it is not necessary before that. This can be achieved by separating the child components into their own NgModule and using the loadChildren property on the parent route. When the router detects a navigation to the people route, it dynamically loads the PeopleModule on-demand. In this article, we have understood how the Angular Router works. βš™οΈ We have seen how you can add routes and redirects to your application, navigate between routes and inject data where necessary. πŸ—Ί We have also learnt how to listen and respond to router events. We now know how to augment routes with guards and resolvers, and lazy-load modules using the router. πŸ’‚β€β™€οΈ Routing is a particularly complex topic which many Angular devs find challenging. Here's hoping this article has broadened your understanding of the Angular Router! πŸ™Œ The Angular Router book by Victor Savkin is a great resource if you are looking for in-depth explanations of the Router's inner workings. The Angular doc site features this tutorial that can help understand concepts with practical examples. Check out all the other great Angular articles on Newline!

Thumbnail Image of Tutorial Angular Routing Explained

When to Use and When to Avoid Using React Helmet

React Helmet is a small library that helps to manage the document head. In this article we will see how to add React Helmet to a project and how to use it. We will learn when React Helmet may improve React applications and when it's not an optimal way in React.React Helmet is a library that helps to manage the document head in React applications. We can use it to change the page title, language, and meta-information. We can work with page <html> and <head> elements using the document object. However, it is not an optimal solution as we need to use React component's lifecycle to add a code to do that. React Helmet provides an easy way to manage the document head information. For this article, we assume that you're familiar with React components basics, such as working with component's properties. You would also need a basic knowledge about the HTML <head> element. Let's start by adding React Helmet to a project: Now, we can use React Helmet to declare changes to the document head. The following example sets the page title, language, and description. We start by importing the Helmet component. Next, we use it to declare tags we want inside the head. We put elements inside the Helmet component. We specify the <title> element for the page title, the <meta> element with name="description" for the description, and the <html> element to define the lang attribute. The Helmet component will move these elements to the document head. The Helmet component supports title , base , meta , link , script , noscript , and style elements as children. We can also set attributes for body and html tags. Description of all available properties of the Helmet component is available on the official site. Let's look at a couple of scenarios where using React Helmet may come in handy. Single page application (SPA) is a common way to implement React applications. With SPAs, we've got a single physical page. We create an effect of transition between different pages by loading different components into the page. The title and other meta-information help users to navigate an application. They also help search engines, such as Google, to parse different areas of SPA application. For example, here's how we can change the page title when switching between pages: We've got two components for pages called Page1 and Page2 . We're using the react-router-dom for switching between two pages. Each page has got the Helmet component that changes the title when a page loads. We can use React Helmet in internationalization scenarios to specify the language of our HTML document. This can be useful when users can select the preferred language. The selected language is used by screen readers and search engines. We can specify the language with the lang attribute of the <html> element. We can use React Helmet with server-side rendering to specify page metadata depending on a path. The server-side rendering is out of scope for this article. To learn about using React Helmet on a server you may check out the using React Helmet on server documentation. There are some scenarios where you may use React Helmet, but more suitable solutions available in React. We can use React Helmet to add CSS styles to our application. We can load external CSS files with <link> element and declare inline page styles with <style> element. However, there are better ways to do that in React. The drawback of React Helmet for loading CSS is that it's hard to maintain a connection between a component and its styles. If we need to load a CSS file for an application, we can define a static <link> element. If we need to load a CSS file only for specific components, we may consider code splitting . For dynamic styling, we can use inline styling or additional libraries such as styled-components or emotion . With React Helmet we can declare script tags to load JavaScript files. The problem with that approach is that it's hard to control when a particular script got loaded. Errors during loading are hard to process as well. For dynamically loading JavaScript files we may use the Code Splitting and React.lazy . For server-side rendering, we may use Loadable Components . React Helmet is a small library that helps to manage the document head. It works in a browser and supports rendering on a server. We can use React Helmet to dynamically set the page title, language, and metadata.

Thumbnail Image of Tutorial When to Use and When to Avoid Using React Helmet