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

What is JSX?

Chances are you, if you've ever looked at a React component, you've seen JavaScript that looks like this: What is that stuff that looks like HTML or XML? That's called JSX and it stands for JavaScript eXtension. It might seem weird to have XML tags in your JavaScript, but it turns out to be super useful. By the end of this blog post, you'll have a solid understanding of what JSX is, and how we'll use it to build powerful React apps. All of our React components have a render function that specifies what the HTML output of our React component will be. JSX is a "language extension" that allows us to write JavaScript that looks like HTML. Let me be clear: when you write JSX, it's really just calling a JavaScript function under the hood. To see what this means, imagine we had a React component that renders an h1 HTML tag. JSX allows us to declare an element in a manner that closely resembles HTML. For instance, let's see a HelloWorld component that shows a message to the user. Without using JSX, we could write this component like the following: It can become cumbersome creating HTML using the function of React.createElement() everywhere, both specifying the attributes of a tag as well as defining child elements, especially when our component output grows in complexity. For example: The same output from above using JSX, more succinctly reads as the following: Using JSX, the component is easier to understand because it looks like HTML (although is not, as we'll look at in a minute). While JSX looks like HTML, it's actually a succinct method of calling React.createElement() . React.createElement() is, essentially, the function which will cause the HTML to be rendered in our browser. As JSX is just JavaScript, we can execute JavaScript inside our JSX. We can execute arbitrary JavaScript inline with our code using the {} curly-brace syntax. For instance, we can add two numbers together inside our component: Although we won't often use a hardcoded math operation in our templates, we can do interesting things with the full-power to execute JavaScript in our templates. Although we won't often use a simple math operation in our templates, having the full capabilities of JavaScript let's us write concise, powerful templates. For example, if we have an array of users in an admin screen, we might want to list the number of users and map over them in a table: And then this JSX template: As JSX compiles to JavaScript we can use the .map operator on an array and then render that list of users into our template. In order to use JSX, we pass our JavaScript code through a "pre-compiler" which translates it into "standard" JavaScript that can be read by all browsers. Typically, compiling JSX is done by using a tool called babel . When you use create-react-app babel is setup for you automatically. We talk about using create-react-app at length in the book , so check it out. Perhaps you've heard that The Virtual DOM is a tree of JavaScript objects that represents the actual DOM. One of the interesting reasons to use the Virtual DOM is the API it gives us. When using the Virtual DOM we code as if we're recreating the entire DOM on every update . This idea of re-creating the entire DOM results in an easy-to-comprehend development model: instead keeping track of all DOM state changes in our head (and in our code), we simply return the DOM we wish to see . React takes care of the transformation (from the old DOM, to the desired DOM) behind the scenes! This idea of re-creating the Virtual DOM every update might sound like a bad idea: isn't it going to be slow? But, in fact, React's Virtual DOM implementation comes with important performance optimizations that make it very fast. The Virtual DOM will: All of this results in an easy-to-use and optimized way to build web apps. The term "Virtual DOM" might seem a bit scary, but really what we're doing is building a tree of JavaScript objects that look like a trimmed down version of the real DOM. (Essentially we're creating a tree of ReactElement objects.) If you want to learn how to use JSX within the context of a project, grab a copy of the Fullstack React book - in there we teach you how to use not only JSX, but data architecture, routing and everything you need to build complete apps.

Thumbnail Image of Tutorial What is JSX?

Props and state of React

Let's talk a bit about props and state , two core concepts in React that we'll use in every React application. The short of it is, props are like the "arguments" (or properties ) that you pass into your components and state stores "component-local data". Let's look at an example to make it concrete: Let's say that we have a <Header /> component that includes a title. The code might look something like this: We want to reuse our <Header /> component in multiple parts of our app. Of course, not every header in our application will have the exact text A title , like this one. It's not convenient to update our component's template directly every time we want a new h1 title. Instead, let's provide the component the header text (the title ) as an "argument". React allows us to send data to a component using the same syntax as HTML: using attributes or properties . This is similar to passing the src attribute to an <img /> tag. We can consider the property of the <img /> tag as a prop that we are setting on a component called img . We can access these properties inside a component using this.props from anywhere inside our component. For example, let's update our <Header /> component so that we can reuse in multiple places. Now we can use the <Header /> component and pass a title as an attribute to have a dynamic value show up: or on the inbox page: We can pass more than just strings in a component: can pass numbers , arrays , objects , and even functions ! What if we want to change something in our component after the props have already been set ? React does not allow us to modify this.props on our components (because it can introduce data consistency issues). Sometimes a component needs to be able to update it's own data. For example, setting an active status for a user in a chat or updating a timer on a stopwatch. While it's preferable to use props as much as we can (that is, pass the data value down from a parent component), sometimes we need to store the local state of a component, within the component itself. To handle this, React gives us the ability to define (and update) it's state . The state in a component is intended to be completely internal to the individual component and it's children (i.e. accessed only by the component and any children it creates). Similar to how we access this.props , the state can be accessed via this.state in a component. Whenever the state changes , the component re-renders (we change state using a special function this.setState() , more on that in a moment). Let's build a stateful clock component using this idea. In order to create a stateful component, we have to tell React we have a stateful component. We do this by assigning a variable called state on the component. Usually, we'll handle this in the constructor of the class, like so: Now that we have the state available in the component, we can use it in our render function. Let's show the current time (from our state ) in our render() function: We'll need a way to update the time in our state object once every second. Let's set this up so that we have a timer that fires in one second and updates the state in our component: Checkout the complete, runnable example in jsbin here . In 1000 milliseconds (1 second), our timeout will fire, which in turn calls this.setState() on the component and React automatically re-renders our component. We'll want to make sure the timeout gets fired on an interval, so every second the state is updated. The this.setState() function accepts a function it will call after the state is updated we can define in the second argument. That's it. Now we have a fully stateful component which we can use inside the <Clock /> component. Now, that we have walked through props and state , we can start building more complex applications. A lot of folks ask, "what if I need to use the current state in the calculation for the next state?" In that case, you need to use a special form of setState -- we talk about it i n our book Fullstack React.

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 Results in Rust

Result s are a fundamental concept to grasp to become a proficient Rust developer, but they can feel a little weird coming from JavaScript. But if we take it slow, they're not that hard to understand: Result is just a way to handle errors with a type . Below, I'm going to guide you through the ins and outs of the Result concept in the Rust programming language. Coming from JavaScript, one of the first stumps beginner Rust developers hit is on error handling . Rust statically types errors and treats them as any other data type, consolidating most of the error treatment code around the Result type . This is a lot different than exception-based approaches, so it's worth a closer look. A Result is a data type that is expected to be returned from functions that can fail in an expected and recoverable way. So put another way, a Result is "just" the return type of a function that is not guaranteed to work. But what kind of functions are not guaranteed to work? Imagine a function that divides two integers. If 6 and 2 are parameters, then the answer will be 3. We might be inclined to think our function's return type is an integer as well, but hold up. Can we guarantee that a division between two integers will always work? Well, let's say we have 6 and 0 as inputs. What should be the answer in this case? What integer would be a valid answer in this case? That's right, there is none; Because 6 divided by 0 is not an integer - here it's a failure. A perfect case for the Result type. Because our integer division function won't return an integer, we need to return something else. In this case, we'll use a Result to wrap the integer when there is a success, or the Result will wrap the explanation of why an integer could not be generated. Because this function is fallible it returns a Result so that the user can deal with its failure properly. This is also an important part of how we use Result : errors that cannot be anticipated, cannot be handled properly upstream. If we want to properly define and type this function, we must know beforehand that it can fail . We must know 6 divided by 0 cannot output an integer and plan for that if we intend to always output the correct data type. An unexpected failure cannot be annotated (because we don't know what it is yet) and it's handling will be impossible. However, an expected failure can have it's failure "encoded" as a Result which will allow us to properly handle the failure case. Result formally tells the caller of a function that the function call can "fail" -- this means the caller is not surprised when the call fails, and we have alternative code paths for when it happens. Common alternative paths involve: One feature of the Rust compiler is that it will require Result to be handled . There are several ways you can do this, if you don't provide and handling code it will cause the compiler to raise a warning. This feature is great because we can be fearless about the execution of our programs -- we know that when the compilation returns no warning flags for our code, we've handled all of the Result possibilities. You might think that the definition of Result resembles JavaScript Errors or Ruby Exceptions . Exceptions on these languages have similar intentions as our Result s here, but there are two crucial differences to note. 1 . Exceptions represent the error, while Results represent the whole outcome Let's think back to our integer division example. The function returns a Result so it can account for the outcome when there is a division by 0 . However, if the division works properly the returned data type is still a Result . The Result is returned either way because it contains the operation outcome as a whole. Now, let's think about Exceptions. We usually see them only when something went wrong . The successful path just returns the naked data type (the integer in our case). In other words, the function would yield the exception or the successful data type. Kind of weird, right? Result gives us consistency because we always get a Result regardless of success or failure. 2 . Exceptions are special, while Results are just a regular type When talking about Exceptions above, you might have taken note of the "yield" verb. Why couldn't I have just used the "return" verb? An Exception is a special kind of data type on languages that implement it. They are generally seen together with verbs like "raise" and "throw", which are reserved keywords used to notify the runtime that something bad happened. Getting more technical, we could say an Exception is thrown, which will reverse the execution stack until it's properly dealt with. This means Exceptions are special to the runtime and have special keywords defined so they can be interacted with. Results, on the other hand, are just a data type that you return from a function. The norm is to treat them like you would treat any other data type. This lowers the cognitive load. Also, because Result is "just a regular type", Result s are part of the type signature for every function they are used in: so you'll never be surprised when a Result is returned. The compiler won't let you be surprised: it will tell you beforehand and make sure you handle it. At this point, I hope you understand the basic rationale behind Result . But let's figure out how to read it and use it in more practical situations. The Result in Rust is defined as an enumeration of two options, with two generic types . Here is the definition directly from Rust's code. The two generic types, T and E , represent the type of the successful and failed outcomes respectively. These values will each be contained by the Result. Each constructor carries one of these types, so we have a constructor for successes ( Ok ) and another for failures ( Err ). Going back to our example, our integer division example returns a Result<u32, String> , which means the operation can either: The construction of a "success", would be the number wrapped by an Ok constructor ( 6 / 2 = Ok(3) ). The failure, on the other hand, would be wrapped by an Err constructor ( 6 / 0 = Err("Division by zero!") ). Say that after we perform the integer division we want to do another operation with the outcome. Let's say we want to divide 6 by 2 , then double the result . We could naively try to multiply the Result by 2, which would promptly yield a compiler error: The error you see is the compiler looking out for us. It letting us know that we are assuming an operation-that-can-fail will never fail. In other words, we are trying to multiply the successful outcome by 2, but we aren't handling the case where the division has failed. So how should the program react in the case where our division fails? Well, in this case, we know the division can never fail since the inputs are the constants 6 and 2, which we know will result in Ok(3) . In these cases, we can tell Rust we are super-sure-and-positive the error will never happen, so just trust us: The unwrap function does this: it removes the Result from the equation. Of course, you're probably wondering, what happens if the outcome was a failure? In our case, the error would be associated with a String type, which cannot be multiplied by two. That's the risk you take when you unwrap a Result . You, as a developer, are taking the responsibility and vowing the Result will never be a failure. If it is, Rust will crash your whole program with a panic . At that point, nothing can stop the inevitable crash. Scary, huh? So what should we do if we are not sure the Result is always a success? Or if you are simply not comfortable taking this kind of risk? For that, we'll use Result matching . Unwrapping a Result is risky. Unwrapping is only safe if there is no way for the error to happen, which is unusual in complex systems. In real-world programs, the arguments often come from the outside (like user input) - we just can't be sure that the division will work or not. For these cases, we would like to know if the operation succeeded or failed without risking a crash. Rust has a powerful pattern matching implementation that works perfectly for us in this case. For example, we could use it to default an error to a constant value (like 0 ), for example: The match keyword lets us test against Result constructors and associate a path of execution to each. And this example above shows how to provide a default value for a failure. But as we said before, we could also pass the error "up the chain". Let's see what it looks like: Now we are passing the problem to the caller, just like the integer_divide function does. If the division fails, we don't know what to do, so we just return the Result . Note that in this case, we have to wrap the successful result in an Ok constructor so function signature is respected. This pattern of unwrapping or returning the result is so prevalent and useful, we Rust developers got tired of writing it every time. Rust has a macro that does just that for us . This looks better, doesn't it? The star of the show here is the ? operator. The funny thing about this example is that both the match and the ? are the same from the compiler's point of view. The macro and operator just make it easier to read. So where to go from here?

Thumbnail Image of Tutorial Introduction to Results in Rust

Svelte Lifecycle Method - beforeUpdate

In Svelte, a component's beforeUpdate lifecycle method is called before the component is updated as a result of a state change. When the component receives new prop values or has its local state modified, the component's beforeUpdate lifecycle method is called before any updates to the DOM are made. Once the beforeUpdate lifecycle method finishes executing, the DOM will be updated with these data changes, which will allow the subsequent call to afterUpdate to have access to a completely synced DOM. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that the value of certain DOM properties, such as a container element's scrollTop , can be cached prior to being updated. Then, these cached values can be used to revert those properties back to what they were originally. Here's a template of how the beforeUpdate lifecycle method is used inside of a component: Note : beforeUpdate is called before the component's initial onMount . Below, I'm going to show you: Suppose you are formatting text within an editable element, such as an <input /> or <textarea /> via a set of controls in a floating tooltip. When you create a selection by dragging your cursor over a subset of the text and click on any one of the tooltip options to transform the text, the selected text should be modified with the selection and focus on the editable element still intact. By default, clicking anywhere outside of an editable element will cause it to lose its focus and current text selection. This does not happen when clicking on any of the buttons in the tooltip because of additional code that preserves the selection and focus. Visit this simple Svelte REPL demo to see how both the focus and text selection can be immediately restored using the beforeUpdate lifecycle method: Demo - beforeUpdate Lifecycle Method - Restore Input Cursor Position In this demo, there are four buttons, each of which transform the input field's text selection differently: When any one of these buttons is clicked while there is a text selection in the input field, the transformText function is called. This function transforms the text selection and sets value to the newly transformed text. Because value is updated with a new value, the beforeUpdate lifecycle method will be called, which checks if input exists (since beforeUpdate is called before the component is mounted) and caches the start and end positions of the text selection. After the DOM is updated and the new value is rendered within the input field, the afterUpdate lifecycle method will be called, which will recreate the text selection based on the cached positions and place the focus back on the input field. If you have built React applications, then you will have probably noticed how beforeUpdate can be used similarly to getDerivedStateFromProps / shouldComponentUpdate / getSnapshotBeforeUpdate . Try rewriting some of the those components that use getDerivedStateFromProps / shouldComponentUpdate / getSnapshotBeforeUpdate as Svelte components that use beforeUpdate . Because beforeUpdate is often used in tandem with afterUpdate , check out the afterUpdate blog post for more examples using beforeUpdate . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - beforeUpdate

Svelte Lifecycle Method - onMount

In Svelte, a component's onMount lifecycle method is called after the first time the component has been rendered to the DOM. For example, if you have a component that is wrapped within an {# if} block, then when this block's conditional statement is fulfilled, the component will be mounted to the DOM, at which point onMount will be called. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that DOM elements within the component will be available for your code to access/manipulate. Here's a template of how the onMount lifecycle method is used inside of a component: Considered the most commonly used lifecycle method, onMount covers a wide diversity of use cases such as... Below, I'm going to show you: When you visit the G-Mail login page, you will notice that the e-mail address input field is automatically focused: This convenience automates away the initial click (or tabbing) into the input field that the user would have to do before being able to type in their e-mail address. Using the onMount lifecycle method, the focus can be moved to an input field when the component is initially rendered. Visit this simple Svelte REPL demo to see how to automatically focus an input field using the onMount lifecycle method: Demo - onMount Lifecycle Method - Login Form When you load the Svelte REPL, the e-mail address input field is automatically focused (indicated by its blue outline). The bind:this directive sets the variable it's passed a reference to an element's DOM node. Here, the emailAddressInput variable is set to the <input type="email" /> element. Since onMount runs after the component has been rendered, the input field will exist by the time this method is executed. Therefore, emailAddressInput will have been set to this input field, and the focus can immediately be moved to it. Note : Automatically focusing into an input field may skip over vital information a user using assistive technologies should be aware of. This may have negative implications on the accessibility of the application. Lazy-loading content reduces the initial load time of an application and reduces bandwidth by delivering only what the client has requested. Imagine having to wait seconds or minutes for a large webpage containing tables with thousands or millions of rows to be downloaded before seeing any content in your browser. Before the webpage finishes downloading, you would have most likely moved on to a different webpage. Wouldn't it be better if you were presented some content immediately (to keep you engaged), and then be shown a "loading" message when you request to view a large table? The onMount lifecycle method can be used to retrieve data from a remote API. This data can then be set to a variable in your component, which will cause the component to only re-render the part of the DOM that's affected by changes to this variable. This is especially useful for lazy-loading a table that contains many records. Visit this simple Svelte REPL demo to see how to fetch motor vehicle collisions data from the NYC Open Data API and render this data as rows of cells in a table using the onMount lifecycle method: Demo - onMount Lifecycle Method - NYC Open Data API Here, we are fetching data from the NYC Open Data Portal, particularly on NYC motor vehicle collisions . Each record of this dataset features the location of the accident, the vehicles involved, the number of fatalities, etc. For fetching data, we are using the native fetch method. The fetch method returns a Promise , so we will schedule an async callback to run when the component is mounted. While the data is being fetched, a "Loading..." message is presented to the user to notify them of the table's status (initially, isLoading is set to true , and this flag toggles this message on/off). Once the data is downloaded and parsed, the collisions variable is set to this data and the isLoading flag is set to false. As a result, the "Loading..." message disappears, and a select number of features of each record are displayed in the table. Note : Alternatively, this can be accomplished with an {#await } block ! Note : Since onMount is not ran during server-side rendering, if you need to fetch data within a component after its initial rendering, then it must be done within onMount and not outside at the top-level of <script /> . Note : Since async functions always return a Promise , onMount cannot return an unmount function since it must synchronously return a value. Event listeners execute code when an event, such as moving the mouse, takes place on the element it's binded to. In component-based applications, event listeners are registered once the component has been rendered to the page. Visit this simple Svelte REPL demo to see how to add an event listener on the window "resize" event using the onMount lifecycle method: Demo - onMount Lifecycle Method - Window Resize As you resize the browser window, notice how the window width displayed in the view changes. Just before the component is unmounted from the DOM, the unmount callback returned from onMount will be executed. This will remove this event listener from window , which will avoid memory leaks in legacy browsers, such as Internet Explorer, that do not automatically garbage-collect event handlers of removed DOM elements. When embedding a widget/plugin from a third-party library, those libraries will need to know where to place the widget/plugin in your application. For example, to display Google Maps via Google's Maps JavaScript API , the first argument to the google.maps.Map method is a reference to an existing DOM element (often document.getElementById('map') ) on the page where you wish to place the map. Visit this simple Svelte REPL demo to see how to embed a Leaflet map into your Svelte application using the onMount lifecycle method: Demo - onMount Lifecycle Method - Leaflet Map The <svelte:head /> element inserts elements into the <head /> element of the document. In this context, we are adding the Leaflet CSS and JavaScript files. By using <svelte:head /> , it keeps all Leaflet-related code encapsulated within a single component that contains all code related to rendering the Leaflet map. When the component is mounted, the <div id="map" /> container element will exist when the onMount callback is executed. The Leaflet library will be able to find this element and initialize the map. Note : This can also be done with Google Maps, but this example uses Leaflet since the Google Maps API requires an API key. To generate this API key, you must provide Google with your billing information in their Google Cloud Platform, and I felt this would add more an unnecessary obstacle to learning how load an embeddable widget/plugin with onMount . Note : If the Leaflet map is toggled on/off, then return an unmount callback that runs map.remove() to destroy the map and clear all of its related event listeners. Let's take the focus input example and refactor it. Instead of having the onMount code (and its contents) in the same file as the component, let's move it into an external module. Demo - onMount - External Module ( onMount.js ) ( App.svelte ) Notice how the bind:this directive was removed from the e-mail address input field. This is because the reference of the DOM node captured by this directive cannot be passed as an argument to the onMountFocusInput method. The DOM node reference will not be available when this method is executed since it is called at the top-level of the <script /> tag. Instead, we can pass an id value so that onMount can query for the input field element once the component that contains it is rendered. Additionally, by moving this onMount code outside of the component, it can be reused for other components that may need to automatically focus an input field when they are rendered to the page. If you have built React applications, then you will have probably noticed how similar onMount is to componentDidMount / useEffect . Try rewriting some of the those components that use componentDidMount / useEffect as Svelte components that use onMount . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - onMount