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

How to create react typescript application with Create React App

The easiest way to create a new app with TypeScript using Create React App is to run this command in a console: Or if you use yarn : Where npx is a package runner that comes with npm 5.2+ and higher. It executes packages like create-react-app or eslint and such. create-react-app is a standard project creator from Create React App. It is used as the template for creating applications. It provides all the necessary dependencies and boilerplate code for a quick start. And --template typescript is a setting which tells CRA to set up a new application using TypeScript. It will create .d.ts file and will set up tsconfig.json . Now you can start the development server and see the result. Console output

Thumbnail Image of Tutorial How to create react typescript application with Create React App

How to Create a React Form: Controlled vs. Uncontrolled Components

In this article, we'll cover two ways to create React forms: the HTML way, with uncontrolled components, and the best practice, with controlled components.We'll discuss concepts such as: what are controlled and uncontrolled components, main tags used in a React form, and form validation and submission.In HTML forms, data is handled by the DOM. In React, on the other hand, the best practice is to handle the data inside the components. This involves storing the data in the component’s state and controlling the changes with event handlers. This may be hard to grasp in the beginning, as it requires you to think about form handling and validations a bit differently. However, it’s also more powerful and gives you more flexibility and control when working with more complex forms. To help you understand the differences between the two methods, we’ll discuss both ways of handling forms in React: the HTML way, which uses “uncontrolled components”, and the best practice, with “controlled components”.  To make things easier to visualize, we’ll build the same landing page for the two forms.  By the end of this tutorial, you’ll be able to build a simple landing page with a functioning React form.  You can find the repository for this tutorial here . Although this tutorial is for beginners and explains the main concepts from scratch, in order to follow through it’s best if you have some knowledge of:  If you're not familiar with these yet, please take a few minutes to go through the pages above before starting this tutorial. In the browser, forms maintain their own internal state. The form data is handled by the DOM, so when you type something in an input field, for example, the data is "remembered" by the DOM. To retrieve it, you need to "pull" the value of the field from the DOM, and this is usually done only once when the user hits the submit button. This type of form is called "uncontrolled" because it relies on the DOM to manage the input data. Uncontrolled components in React are similar to HTML inputs, as they "remember" what you type in. Here's an example of a simple uncontrolled component. If you want to access the data from uncontrolled components, you need to use a ref . Refs allow you to reference a DOM element or class component from within a parent component. Refs allow you to “pull” the value from a field when you need it, so you can do it when the form is submitted, for example. This means less complex code for you, but it also means that you’re not able to handle validations in real-time.  Also, if you opt for uncontrolled components, you can’t disable the submit button for example and you can’t enforce a specific format for the text input as the user types something in.  All your validations will happen on submit, which can be quite annoying for the user, especially if you’re building longer forms with a lot of input fields.  However, uncontrolled components are the easiest way to create forms, and if you don’t really need to do much validation, you can safely use them.  Here's an example of a controlled class component. The callback function is controlled by the parent component - so the Form in our case. The new values of the state are passed to the input fields as props.  Since the value of the input field changes whenever you type a new character, so the state changes continuously.  This may sound bad but it’s actually useful, as the Form component is always “aware” of the state and the value of the input. Thus, if you want to validate something, you don’t need to “pull” the state value on submit and then display error messages.  For example, if you don’t want the e-mail address to include “@gmail”, you can display a validation message in real-time, and this contributes to a better user experience.  Let’s start by initiating a new React app, using Create React App . I’ll use VSCode for this tutorial. First type this command in your terminal:  npx create-react-app form-demo Then, move into the form-demo folder, and in the terminal, type npm start to run the app in your browser.  To speed things up, I’ll use react-bootstrap for the layout of the landing page, and an icon from bigheads.io to make the page a bit nicer. You can grab the image here . To install react-bootstrap , type npm install react-bootstrap in the terminal. Then, because this library doesn’t come with a predefined version of bootstrap, you’ll need to install bootstrap as well and add a CDN link in the index.js file, like below: npm install boostrap Now in the App.js file, add the following code to start creating the page layout:  If you save and reload the page, your app should now look like this:  Let’s start building the form component. In the src folder, create a new file called Form.js and add the following code:  Next, replace the comment with the form fields:  At the moment this isn’t a controlled component, as we’re not using state or props. So let’s add that to the form. First, add the constructor right under the SignupForm class. Then, add the props to the form fields:  We’re doing two things here:  So we now need to define the onChange functions, and we’ll do this right under the constructor:  If you reload the page and add something in the name field, you’ll get this error:  That’s because we have to bind the updateName and updateEmail functions in the constructor, like this:  So now if you refresh again and inspect the form, you should see the input value changing as you type:  Let’s add a checkbox to the form, to get the user’s consent for contacting them when this app launches.  To align the checkbox to the rest of the input fields, I’ve used an offset of 2 columns.  Next, we need to initiate the value of this checkbox in the state object. We’ll assign it a boolean value, which will be false by default.  Now let's add a handler that will update the state on change. Finally, we need to add a handler for submitting the form. The handleSubmit callback function will be called when the user clicks on the submit button. We've added event.preventDefault() because we don't want to redirect the user to a new page when the form is submitted. Let's not forget to bind this function in the constructor as well: If you now reload the page and submit the form, you should see the alert message displayed: Before submitting the form, we want to validate the input fields to make sure they're not empty. This will happen purely on the client-side, so in the browser, not on the server-side. By doing so, we can display error messages in real-time, to let the user know that the values added in the input fields aren't meeting the validation criteria. To do the validation, we'll add another property to the state, called touched , which will keep track of the fields that are changed by the user. Initially, none of the fields have been touched by the user, so there's no point to validate anything. We'll therefore initiate both the name and the email values here as false : We want to know when the user interacts with these fields, so that we can run the validation function. So we need to add a new handler called handleBlur , which will update the touched values if the fields are touched: So now every time the user interacts with the name or e-mail fields, the touched value is set to true . Finally, let's make sure that the name field isn't empty, and that the e-mail address includes an "@" character. We'll define a new function called validateFields , as follows: So we're first checking if the name field was touched. If it was, and the length of the string typed by the user is lower than 2, then we're displaying an error message. Next, let's add the e-mail field validation and return the error value: This function needs to be invoked in the render method, because we want to validate whenever there's a change in the input fields. So basically whenever the form is rendered again. So let's add the validation function to the form, right under render : To display the error messages, we need to add some new elements to the form. To know if the fields have been touched, we need to add the handleBlur function to both name and email , like this: Don't forget to bind the handleBlur function in the constructor, as we did with all the previous functions. Let's test our validation! If we refresh the form, we should see our error messages in real-time: Before sending the form, let's initiate a git repository and push all our changes to GitHub. You can access the repository here . The last step in this tutorial is to send the form when the submit button is pressed. We'll use axios for this, so let's first install it by typing npm install axios -save in the terminal. To make use of it, go to your Form.js component and import it. Next, let's rework our handleSubmit function to make a post request when the form is submitted. We'll use the json.placeholder.com API for this, and we'll send the state object. Now if you reload the page and submit the form, you should see the response logged in the console. That's it, now all you have to do is replace the post endpoint with your actual backend endpoint and you're good to go. For the uncontrolled form, we'll use a sandbox. You can find the final exercise here . Let's first create the form component, in the App.js file: Next, we'll initiate the constructor and bind the handleSubmit function, then we'll add the handler to the form. For the input fields, we mentioned that we have to use refs to retrieve the value. First, let's add them to the constructor: Next, we'll add the refs to the form controls: Let's check if this works correctly by displaying an alert message with the name and email value when the form is submitted. If you now submit the form, it will display the two values: All works well, so let's style the form a little. I'll add react-bootstrap and bootstrap as dependencies to the project. We also need to import the Bootstrap styles into the App.js file, like we did in the previous example, and to redo the form fields as follows: Now let's add the image and refresh the project. Your landing page should look like this: Next, we need to handle the checkbox. At the moment, it defaults to false , so if we add this value to the alert message, we see that it doesn't change when the checkbox is checked. To handle this, we need to add another ref . First to the constructor, then to the form input field. To test if it works correctly, let's display the value of the checkbox as an alert message when the form is submitted. The form works correctly. Finally, let's post this to the same API endpoint that we used for the previous form. That's it! You now know how to create React controlled and uncontrolled forms. As you can see, creating uncontrolled forms requires less code and is easier, but the controlled components offer more flexibility and a better user experience. If you'd like to continue learning React, check out the:

Thumbnail Image of Tutorial How to Create a React Form: Controlled vs. Uncontrolled 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

    Black Friday 2020 Sale!

    It's Black Friday and to celebrate we have our biggest discounts of the year today. We're offering discounts in three ways: These discounts are available only for this weekend - and our discounts will never be lower, so this is your chance for our best offer. With newline Pro you get access to over 500 lessons, thousands of pages, across all of our books and Guides. You get full access to our best-sellers like Fullstack D3 , Fullstack React with TypeScript, Fullstack Vue and tons more With newline Pro, you also get Early Access to new Guides like: The JavaScript Developer's Guide to Rust and The React Developer's Guide to Clojure . We have 30+ new Guides scheduled this year that go in-depth into the wide range of things you have to know as a developer in 2021. We'll be raising the price to newline Pro as the library grows, but if you subscribe now, you can lock in your price for as long as you stay subscribed. Join newline Pro here

    Getting Started with GraphQL in React using Apollo Client

    Apollo is a great interface for fetching and managing data through GraphQL. When we’re building applications with GraphQL, it’s important to manage data effectively to have a smooth development experience. This is where Apollo steps in, and acts as an abstraction layer over GraphQL (which is just a query language) , and provides a robust platform for data fetching. The power of Apollo lies with how much we get out of the box (it’s a lot). We don’t need to do lengthy custom setups or configurations and can get started right away. Here, we’ll be discussing the benefits and usage of Apollo Client with ReactJS, but it’s important to note that most of the same features are also available in Angular and Vue. Before we dive deeper into Apollo, let’s briefly discuss GraphQL. GraphQL is a query language, built by developers at Facebook that emphasizes predictable results by building schemas for building queries. We use a tree structure to fetch data through a single central API endpoint. With traditional REST APIs, we are usually exposing multiple APIs for different purposes. For example, we might have an API to fetch books, and a different API to fetch authors. Similarly, we may have APIs to get a singular book or author. With GraphQL, we only hit a single endpoint, but we use fields to fetch only the data we need, such as only the name of the book, in a sea of different available parameters made available by the back-end. By making a single request, our application can be fast even on slow mobile networks. The type system of GraphQL keeps the API structure robust, and the dev tools help us see the schema definitions to easily debug our requests. Moreover, it solves the problem of over-fetching and under-fetching, as we’re able to get exactly the data we need in one hit. Its optimistic UI and caching make all interaction with the server super fast and snappy. On the server-side, we import the required libraries and create schemas for Queries and Mutations, respectively. This prevents us from spending time thinking of complex API flows. Queries are used to read data, whereas Mutations are used to create, update, or delete the data. Here is a very basic example from the GraphQL documentation: First, we build the schema where all our possible queries lie, Now, we can create a root resolver that hosts all our functions corresponding to the queries we have created: Finally, we can initialize our application with GraphQL. The algorithm itself is very simple, it resolves each field before diving inside and doing the same until all the fields are resolved. After that, the result is returned in the required format. To describe and initiate our queries on the front-end, we can use the graphql library to hook into our React components, this will give us our resultant data as props. More often, people choose to go with libraries such as Apollo and Relay. Here, we’ll be discussing how Apollo specifically provides us with a toolkit to make our lives easier when working with GraphQL. Firstly, we need to include the required functions from apollo-client, apollo-link-http and apollo-cache-inmemory. We can create a client instance through ApolloClient, where we’ll pass two things: Now, we can call our query function with the defined query. Here, we’re getting all books for authors that are aged less than or equal to 25. Note, we’re using the JavaScript template syntax to write our queries. If using the graphQL extension, it will also provide us with syntax highlighting. We can do much more with queries like this, for example, we may choose to hit a different resolver to get all the books of a specific author. As Apollo uses Context API under the hood, to enable it to access our components, we need to wrap our root element with ApolloProvider. Next, we need to define our query. It’s better to create a folder structure where all our queries and mutations are in specific folders so it’s easier to navigate during development. Here, we’ll create a userQueryBooksByAuthor.js file, where we’ll define and export our query. Now, we can import this in the file for our React component where we’ll be calling this query and use it with the hooks Apollo provides. useLazyQuery allows us to query programmatically on events. For example, we click a button to load the books, in that case, the click handler function will look something like this: And to call it: Here, we’re passing the authorName from our click function, but we could also have this come from anywhere, such as a state variable. If we wanted to run the query every time a component loads, we can call the useQuery hook instead, in this way: Now, all we need to do is conditionally render our data. We can simply do that in our return statement in this fashion: Mutating data with Apollo Hooks is just as easy. We can call the useMutation hook, pass in the required variables to update our data, and get our results back. First, we initialize our hook and create our useMutationUpdateAuthorName.js file in our mutations folder: And, Now, we can call it conditionally. Like before, we’ll call the mutation on a button click. And to call it: Typically, when we’re working with REST APIs, we need to have some sort of state management solution for our React apps. This is because we need to keep track of our data, loading states, and success/error responses. This can sometimes make our code harder to navigate. However, Apollo provides us with caching as well as variables that hold the loading and API call result states directly. This means we don’t need to create further state variables, as we can just fetch them out of the query or mutation that we run as seen in the previous example. Moreover, we don’t need to store the fetched data in state either. Since Apollo caches all the results, if we query for the same data again, it will avoid making unnecessary API calls and instead look into the memory first to find a cached version of the call. From experience, it's clear that GraphQL is being considered more day by day by developers against traditional REST servers. One common use-case I’ve encountered is fetching data from Content Management Systems, where a specific data model is defined. This makes it easy to think of our data in a tree structure and to fetch what we need based on conditions quickly and efficiently. There’s no doubt that it allows developers to think of a different approach when handling data management between clients and servers. And Apollo is right at the forefront, providing even more features and possibilities to make things convenient for developers.

    Thumbnail Image of Tutorial Getting Started with GraphQL in React using Apollo Client

    Deep dive into the Node HTTP module

    An in-depth look at the Node HTTP module, and how to use it to scale up!The HTTP module is a core module of Node.js, it is fair to say it's one of the biggest responsible for Node's initial rise in popularity. HTTP is the veins of the internet, this website, any site you explore, you use the HTTP protocol to request it from a server, and the server uses the same HTTP protocol to send you back the data you requested. Let's import the module and create a basic HTTP server with it We just created an HTTP Server object, some of its methods are: For a complete list of HTTP server class properties and methods, check out the official docs . In the example below, let's use the callback function to handle HTTP requests and respond to them. req : shorthand for request, is an object from the class   IncomingMessage  that includes all the request information. Some interesting properties are: It's also good to remember that the IncomingMessage extends the <stream.Readable> class, so each request object is, indeed, a stream. res : shorthand for "response", is an object from the class ServerResponse, which contains a collection of methods to send back an HTTP response. Some of the methods are: Each time we write response data with .write(), the chunk of data we passed gets immediately flushed to the kernel buffer. If we try to .write() after .end() has been called, we will get the following error: In an HTTP post request, we usually get a body as part of the request. How do we access it using the Node HTTP module? Remember the request object is an instance of the IncomingMessage class which extends the <stream.Readable> class, in post request we can access the body as a stream of data like this: You could use an application like Postman , to launch the HTTP request to our application, and you would end up with something like this: While you are in Postman, be sure that you are firing POST request. You will also need to set the following configuration in order to set the 'content-type' headers as 'application-json' To handle HTTPS requests, Node.js has the core module https , but first, we need some SSL certificates, for the purpose of this example let's generate some self-signed certificates In your command line (use GitBash if you are on windows) lets run Now let's use the HTTPS module to create an HTTP server The main difference is we now have to read the key files and load them into an options object, that we pass to .createServer() to create our new shiny HTTPS server. Sometimes we would like to do an HTTP request in order to gather data from a third-party HTTP server. We can achieve this by using the Node HTTP module .request() function. In the following example, we will be calling the postman-echo API which returns whatever we send them. But I would suggest instead of using the core HTTP module for sending requests, you use something more sophisticated and user friendly as Axios . The pros of using something like Axios, is promise abstraction, easier to manage errors on requests, and support for really valuable plugins, like Axios retry. In a lot of situations, we can use a framework like Express to create a server instead of doing directly to the HTTP module. Install express using npm in your command line Express will give you a more elegant way to handle all your API routes, handle session data, and will provide you some plugins for authentication, Express is gonna make your life way easier! We've been through a lot, within this short post, but with these few examples, you should have a good grasp on the core functionalities of the HTTP Node core module. It's ideal to understand the inner functionalities of the HTTP module, but for more complex tasks is recommended to use an abstraction library, such as express in the case you are building servers, or Axios in the case you are creating HTTP requests. 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!

    Thumbnail Image of Tutorial Deep dive into the Node HTTP module