Tutorials on React

Learn about React 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 Use useCallback Hook with TypeScript

The useCallback hook returns a memoized callback that only changes if one of the dependencies has changed. This helps us to avoid unwanted and unnecessary components re-renders. The basic syntax for the useCallback hook is: You don't need any additional typings since TypeScript knows that useCallback accepts a function and an array of dependencies. It is preferable to use eslint-plugin-react-hooks though, to ensure you don't miss any argument in the dependencies array but that's optional. Let's assume we have a login form component: And then we have 2 input components: The problem is that when we change an email React will re-render both inputs instead of only EmailInput . This is happening because handler functions are being created on every re-render of the LoginForm component. So, on each render there are new handler functions for the InputEmail and PasswordEmail component, that's why they re-render each time. Let's fix that! Now, when we change an email or a password only the corresponding input component re-renders.

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?

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

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.

How to Use react-hook-form with TypeScript

React Hook Form is a library that helps you to simplify form validation. It uses React hooks to inject required validation checks and to bind a form and a submit handler. Let's create a signup form with React Hook Form and then type it with TypeScript. Out form will contain 3 fields: To connect the form with validation checks we will use useForm hook from the React Hook Form API: Here, we use register as a value to ref prop on each input. It binds the input with validation. We need to pass the name attribute as well since register relies on it. Also, the name must be unique for register to work properly. The handleSubmit function will call the provided callback if validation is successful. In our case, it will call onSubmit callback and log out all the data from the form. Now let's create a type for form data. Let's call it User : When type is created we can use it to annotate the form data: To make an input required, we can provide register with a settings object. When we specify the required field as true , the validation returns an errors object. We can use this object to access errors on every field in the form: We can also specify a required pattern for each field to perform custom checks:

Using React Redux with TypeScript

In this article, we will learn how to use react-redux hooks with TypeScript to build a note taking app.Redux is an incredibly useful tool for centralised state management in React apps. However, introducing Redux into a React project can be a bit intimidating because it introduces a number of new concepts - state, actions, reducers, selectors, action creators etc., and adds a fair bit of boilerplate code. This has, however, changed for the better since the introduction of react-redux hooks such as useSelector and useDispatch . In this article, we will learn how to add Redux to a simple React TypeScript app, and how to use and manipulate application state. We will use create-react-app to generate a stock React app. We can generate a TypeScript-based app by specifying the template argument as below. We'll call our app react-redux-typescript . Once this is done, the next step is to add redux and react-redux to the project, like so: Since redux is written in TypeScript, we don't need to install any additional types for it. We do, however need to install the types for react-redux . We can then open the project in our code editor and start hacking! 🤓 We can remove the default layout generated by create-react-app in App.tsx and replace it with the following initial layout that includes an input for typing in a note. It will be useful to separate the note input into its own component for ease of use and modification later on. So we can create a new file NewNoteInput.tsx with the following layout. So our App.tsx will now look like this: Now, we'd like to know when the 'Add note' button is clicked, so that we can add a note. We can do so by defining a function prop for the NewNoteInput component, which gets called each time the 'Add note' button is clicked. The NewNoteInput component now takes an addNote function that takes a string input for a note. The component also maintains an internal state for the current note being typed. This value is updated on each change of the note input element. When the 'Add note' button is clicked, the onAddNoteClick function is invoked, which calls the addNote function passed in, and cleans up the internal state. It's important to note the types we've used here: We can then use the addNote prop in App.tsx to pass in a callback. For now we can use alert to make sure that it's working. eInput addNote={alert}/> We are now ready to introduce Redux into our app! The first step towards this is to create a reducer. Reducers are pure functions that are used to populate new values for any piece of state. A reducer takes two parameters - the previous state value, and an action that contains a payload that is used to a'er the state value. Let's create a notesReducer.ts file that contains this function. Here, we have defined an interface for NotesState which includes an array of notes that have been added. The initialState represents the state at the point when the app is loaded, where there are no notes saved yet. We have also defined a type for Action , which contains a type ADD_NOTE and a string payload which is the actual note to be added. We can now create a Redux store that manages the state of our application by using our notesReducer . We can create a store.ts file to hold this object. The final step to connect it all up, is to wrap our application in a react-redux Provider. In the app's index.tsx , we will import Provider from react-redux and wrap our app in it. The Provider takes a store prop to which we will pass the store we have created previously. Previously when building the layout in our App.tsx file, we used a placeholder to indicate the list of added notes. We'd now like to populate that list with real data, and for that we will need to access the state of our app. We can access this state using the useSelector hook from react-redux . A selector is a function that parses the state and gives back the required slice of it. In our case, we'd like the notes array from the state, so we can access it like so: The useSelector hook takes a function that receives the state as a parameter, and returns a specific part of it. It also accepts two type arguments: We then use the notes array to render a list of notes. We're now displaying live data from the state in our application. However, there is no data to display since we're not adding anything to the state store in the first place! We are still passing in alert as the addNote callback to NewNoteInput . Instead, we need to pass in a function that will dispatch an ADD_NOTE action which will trigger the notesReducer and add the note to the state. react-redux provides a useDispatch hook that gives us access to a function that can dispatch actions to our store. We can use it with our addNote callback to dispatch the ADD_NOTE action. In the onAddNote function, we have manually defined the ADD_NOTE action in the format expected by the notesReducer . This can, however, open up many possibilities for errors - we could make an unintentional typo, get one of the property names wrong, or assign the wrong values. react-redux offers a feature called Action Creators which helps avoid these errors. To make use of this feature, we can create a new file, say actions.ts , that will define our action creators. We can move the definition of the Action type into this file as well. This means that any component that calls the addNote function only needs to be concerned about the note itself, rather than all the other formatting around the actual action. We can now refactor App.tsx to use this action creator. And there we have it! We are now displaying the notes from our app state in the list, and adding to the list each time a new note is added. ✅ All the code from this article is at https://github.com/satansdeer/react-redux-typescript.

Handling File Fields using React Hook Form

In this article, we will learn how to handle file uploads using react-hook-form.react-hook-form is a great library that provides an easy way to build forms with React. It provides a number of hooks that simplify the process of defining and validating various types of form fields. In the following sections, we will learn how to define a file input, and use it to upload files to firebase. We will use create-react-app to generate a stock React app. We'll call our app react-hook-form-file-input . Once the app is ready, we can navigate into the folder and install react-hook-form . Let us define our form in the app.js file. We can remove all the default markup added by create-react-app , and add a form element which contains a file input and a submit button like so: We can now connect our form element to react-hook-form using the useForm hook. useForm returns an object containing a register function which, as the name suggests, connects a given element with react-hook-form . We need to pass the register function as a ref into each element we want to connect. Now that our file input has been registered, we can handle submissions by adding an onSubmit handler to the form. The useForm hook also returns a handleSubmit function with which we will wrap our onSubmit handler. The data parameter that is passed to onSubmit is an object whose keys are the names of the fields, and values are the values of the respective fields. In our case, data will have just one key - picture , whose value will be a FileList . When we fire up the app using yarn start , we will see this on screen. On choosing a file and clicking 'Submit', details about the uploaded file will be logged to the console. Now that we have learnt how to work with file inputs using react-hook-form , let us look at a slightly more advanced use case for uploading files to Firebase . You can find the code for the Firebase file upload example here . Clone the repo and run yarn to install the dependencies. You can set up your Firebase configuration in the .firebaserc and firebase.json files at the root of the project, and log into Firebase using the CLI . As we've seen earlier, we can install react-hook-form via yarn using: The App.js file contains a file input which uploads a file to Firebase. We can now switch it over to use react-hook-form like so: We have wrapped the input element with a form , given it a name and registered it with react-hook-form . We have also moved all the logic in the onChange event handler into our onSubmit handler which receives the data from react-hook-form . We can run the app using the yarn start command and it will look the same as earlier. Choosing a file and clicking 'Submit' will upload it to Firebase. We have now learnt how to work with file inputs using react-hook-form . ✅ The code used in this article is available at https://github.com/satansdeer/react-hook-form-file-input and https://github.com/satansdeer/firebase-file-upload .

Thumbnail Image of Tutorial Handling File Fields using React Hook Form

How to Handle Effects Using Hooks in React with TypeScript

There are 2 hooks to handle side-effects in React: The first one fires after layout and paint, during a deferred event. The second one works synchronously before the next paint, and used to handle effects that are visible to a user. The useEffect hook accepts 2 arguments: By default, useEffect fires on every re-render. If you need it to fire only when certain values change use the second argument to point out those values. You can also return from an effect a clean-up function. The clean-up function runs before the component is removed from the UI to prevent memory leaks. You don't need any additional typings for the useEffect hook. However, TypeScript knows about its inner structure and type signatures, so there is no chance to compile something like: This hook is the same in a sense of type signatures as the useEffect hook. So you can re-write a counter component using it: It also doesn't require any additional typings.

How to Use useReducer with TypeScript

The useReducer hook is a hook that allows you to create a state, update it, and share its data across different components. (Its core logic is similar to Redux .) It takes a reducer-function and an initial state as arguments and returns a tuple of a new state and a dispatch function. The reducer must extend the Reducer<State, Action> type, which is a function that takes a state and an action as arguments, updates the state, and returns the updated state: A state is usually an object with some data. Let's use a counter as an example. If we want to keep track of a current counter value, we can create an object with a value field: We will use this State type as a type parameter for the Reducer type later, and the initialState object will be the default value for the state. An action is sort of like an event, which triggers the state updates. For example, a counter can have 2 actions: for increasing and decreasing its value. Usually, an action is an object that has a type and payload . The type is like an ID of this action, and a payload is a data that the action transfers. Now that we have a state and a set of actions we can create a reducer. When a reducer is ready, we can use the useReducer hook. Now we combine our initial state, reducer, and actions with a component:

How to Use React Refs with TypeScript

Refs provide a way to access DOM nodes or React elements created in the render method. Also, they can be used to store some references to entities or objects for accessing them later. To use refs with functional components use a special useRef hook . It is a generic function, so we can pass a type-parameter, that will tell TypeScript what type is acceptable for this ref. Initially, we set a ref's value as null , because it will be set later on render. That's why we need to null-check inputRef.current later in onFocus . Also, inputRef itself is an object that contains a value in the current field. So to access the real element we need to get a value of this field. In class components, you can store refs in private class fields after creating them with createRef . When you need to access some data but you don't need to share it across components and don't need to change it you can use refs too.

How to Use React Context with TypeScript

React Context provides a way to pass data through the component tree without having to pass props down manually at every level. Use it when you need to share data “globally”, between many components on different levels to a component tree. To create a context use React.createContext : With TypeScript, you can declare a type for a context , so that TypeScript will know what types are acceptable for this context. However, there is a catch. If we have a data structure that can't have default values we can't just type a context: There are 2 workarounds here. The first one allows not to assign values to fields of a User type. So when we pass a defaultUser as an initial value there no errors: But in this case, we lose in type-safety a bit because we can miss some values later. The second option is to set null as an initial value: This way we don't lose in type-safety, but we will need to check if the context value is null every time we access it. When created, a context can be used in components. To give access to a context value we need to use Provider : The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider . To get a value we need to use the Consumer component: It uses a render-prop pattern . This means that it accepts a function instead of a component as a child. It will then pass a context value as an argument to this function. You can also use useContext hook to get access to a context value. This makes the component's source much simpler and cleaner.

How to Use State in React Components with TypeScript

When you need to store some data that won't be shared across components you can use the local component state. To use state in functional component use useState hook. This hook returns a tuple of two values. The first one is the current value of the state, the second one is a function to update the state. You can also increase type-safety declaring what types a state accepts: In class components, you can define a state as a class property called state . With TypeScript, you can declare a type for the state: The CounterProps type is used to declare what type the properties of this component support. The CounterState type will check the state types at the pre-compile time, so you will know earlier if there is an error. You don't have to annotate CounterState the second time inside of a component itself, but it allows better type inference when accessing this.state. Notice the React.Component<CounterProps, CounterState> type. This is the generic React.Component type. It takes two type-parameters that tell TypeScript how to interpret types of component props and state, so TypeScript can derive types of each field in props and the state. There is no need to mark types fields readonly since React.Component<P,S> already marks them as immutable. To change state in a class component use the setState method . This method enqueues changes in the state and causes a component to re-render.

TypeScript and React - how to prevent bugs by typing props, state, and hooks

TypeScript is fantastic to use with React because it can help us catch a lot of bugs we wouldn't catch otherwise. It helps our team have good documentation and it makes React easier to use (over the long term). But there were a lot of things I didn't understand in the beginning that I wish someone would have explained to me. In this post, I'm going to walk you through the basics of using TypeScript and React, with code. We're going to look at: The key idea is that we want to define the "shape" of our props and state with TypeScript types -- and TypeScript will ensure that everything conforms to the right "shape" in our code. Here's the interface we're going to be using for props and state throughout this post: So for getting started, thankfully, create-react-app has a typescript template that has everything setup for us! You can create a new project like this: It will create a bunch of files and the main addition is the tsconfig.js file which configures the TypeScript compiler. You'll also notice that our files end in tsx instead of jsx . Also you look at the package.json you'll see some extra typescript packages, too - but because they work out of the box, we'll ignore those for now. The main thing we're going to be doing with TypeScript and React is defining components. So it makes sense to look at the typing of those components first. As you may know, there are two ways you can define components: Let's look at both: To keep it simple, let's take the classic case of a component that shows a counter with a message. A bare-minimum TypeScript class component looks like this: So far, so good, but we're missing two key parts of React components: In React, we use props to pass down values into a component and state to manage state within a component. If you think about it closely, props and state are both objects that need to have a type . Often we might have a component that has half-a-dozen props that could be passed in and we want to make sure that these props are valid keys AND valid values. One of the great things about using TypeScript with React is that the compiler will enforce this for us. So let's define an interface for the props to this component. We want to accept a message into this component as props like this: If you think about it, what we're doing is passing this object into the component: We can define an interface in TypeScript that describes this object. We'll do it like this: But how do we tell React that the CounterProps interface is the types for our component props? We do this by using TypeScript generics on the React.Component type. You can think of generics as parameters to a type . Generics let you make "configurable" types. It's easier if we look at the code: Now let's say we try to call this component without passing a message prop like this: ... we get an error! Here's a screenshot from my VSCode: There's a lot there, but the key point is that it's saying Property 'message is missing' Okay, so we know we need to pass a message prop. Let's try passing an invalid message prop and see what happens: Above, the number 123 is invalid because we defined our message to be a string (not a number ). Here's what I get in VSCode: Again, a lot there but the key idea is that it tells me: Type 'number' is not assignable to type 'string' Pretty cool! Okay so that deals with typing props, what about state? We deal with that much the same way, first we'll define an interface for the state: Let's keep our counter in state as the variable count : Now we pass the CounterState as the second parameter to the React.Component generic: Looking at the above code, you might be wondering, how would I ever know that state was the second generic parameter? It's in the documentation (for the types). Just like how you learn the order of function parameters in, say setTimeout , you look at the docs to learn the order of parameters for generics. Typing class components is interesting, but they're also falling out of fashion. So how would we type functional components? Well, the first way is that you don't have to add any types at all . Because we are returning JSX, TypeScript can automatically conclude that the return type of our function is JSX.Element , which is good enough for React. Of course, if you want to be verbose, you can use React.FC : But what about props? Well, with a functional component, props are just arguments so we can just type the arguments: Above we type the props as CounterProps . However, a more idomatic React style would be to destructure the props into variables like this: What about functional state? When we have a functional component we use hooks to manage state. Specifically we're going to use the useState hook. Here's what our component looks like with keeping a basic counter with useState : So in this case, if I was keeping simple values we don't need to add any extra types at all. If we keep one value within useState , it's pretty easy. Buuuuut if you've worked with React long enough you're probably suspicious of my solution here. What about in the more complicated case where our state is an object , like in our class above? Say we want our state to be the same CounterState object: To type this, we use the generics on useState : Above, notice the line with useState<CounterState> - there, we're telling TypeScript that the object in useState is of type CounterState - and so it needs to enforce that "shape" on any value it controls. So there you have it, that's the absolute basics of using React with TypeScript. You can get pretty far on just the above tips. But there's still a lot more to learn like: We cover the answers to these questions and more in  Fullstack React with TypeScript . .

Thumbnail Image of Tutorial TypeScript and React - how to prevent bugs by typing props, state, and hooks

A Guide to React createContext with TypeScript

In this post, we will dive into a technique for sharing data between React components using Context . While we usually use props to pass values, that doesn't always work if we have components in different parts of our component tree. We can use Context to share these values anywhere in our app (and we can use TypeScript to type them). Below, I'm going to show you: By the way, Context is an intermediate React topic. We cover this more in depth in Fullstack React with TypeScript . This book will help both experts and React beginners develop advanced React and TypeScript skills. Check it out . React already provides us with component state to track data in components, so why do we need a different way to track data? Component state only works inside each component. and can't share that data with other components unless you e.g. pass it using props. But with larger apps, some of the data that is shared across components might include: Context creates this common dataset that all components use. Context is a way where React apps can share data between different components. Again, the key point here is that these components don't have to have a parent-child relationship. They can be in completely separate parts of your app -- as long as they access the same context, they can share data. A Context object holds any data we assign: numbers, strings, objects, functions, arrays, etc. Here's how you create a Context with React and TypeScript: React provides us the React.createContext function. It takes any data type. In the example, I'm passing it an object with a userName property and a profilePic property. Of course, we're using TypeScript so we want to type the object in context. We could do it like this: Then to use this type, we'd use a generic when we call createContext : To see React Context in action, consider this example for localizing a weather app. In this app, we want to show weather reports in 4 different languages. The user is able to change their language or locale selection at any time. We'll support English, French, Japanese, and German. In addition, weather information must be translated to Fahrenheit or Celsius depending on the locale. Here's what the app's default interface looks like with locale set to "English (US)": Here's what it looks like when the locale is changed to "Japanese (JP)": This is how we used Context to solve this problem: These are the same general steps you will take when creating and consuming a Context in your own apps. We create a LocaleContext using the React.createContext function. It looks like this : This creates the LocaleContext . The next step provides it to the app using a LocaleProvider . We do this in our main App component: Regular components in the component tree access the values stored in the LocaleContext and use them. Here's what this looks like : Q: Does this mean that you don't need to use state anymore? A: You still need state for handling data specific to a single component. Context is for global data. Q: What about hooks like useState and useEffect , do they work with Context ? A: Yes, there's nothing that prevents you from using these parts of React with Context . We have just released Fullstack React with TypeScript This guidebook will teach you the skills you need to how to use React and TypeScript confidently in your work. You can get a copy here:

Thumbnail Image of Tutorial A Guide to React createContext with TypeScript

Thinking in React Tutorial: a custom hook to capture keystrokes in TypeScript

Thinking in React can feel weird if you're not used to it. In this post, I'm going to show you a React-way to think about and use the native browser's APIs and hook them into your React app. Specifically, I'm going to show you how to listen for keystrokes in a React-y way. Keyboard shortcuts are making a comeback in webapps -- but this pattern is more than listening for keystrokes: it's a way of thinking: the React Way. Here's what we're going to build: You can find the completed Codepen here : We're going to build a custom React hook that listens for keystrokes and lets us know when a certain key is pressed. As you might have guessed, we have a book that teaches intermediate React patterns with TypeScript . It's called Fullstack React with TypeScript and you can get a copy here In this post, we're going to look at: When we're done, we will have a custom hook called usePressObserver . usePressObserver will accept a watchKey argument, which specifies the key we're watching. It will return a pressed variable which will either return true or false depending on if the key is pressed down. We can use that pressed value in another component. In this case, we'll pass it as the active prop to the Button component: So how do we get there? You can listen to any key press by listening to the "keydown" event, like this: And you can listen to any key release by listening to the "keyup" event, like this: Now, what is the second argument here? handlePressStart and handlePressFinish are callback functions -- that is, functions that the browser will call whenever the appropriate event happens. So far, so good, but if we're using React where do we even put this?? If we just throw a document.addEventListener into a component we will add a new listener on every re-render . Not what we want. Does React provide any functionality that will allow us to only call a function only once? Yes. Well, sort of. The useEffect hook lets you perform side effects . The API to useEffect looks like this: effectFn is a function argument . That is, it is the function that contains the effect we want to do. We'll look at that in a moment. arrayOfThingsToWatch is an array of variables which React will watch. If any of those changes, React will call the effectFn again -- but if they don't change, it won't be called again, which is exactly what we want. So pseudocode of what we're trying to do looks like this: So let's fill in the blanks. The first thing we want to do is define our custom hook. Here's the skeleton: We start by defining a Settings interface, which defines our options for this hook. In this case, we'll just have one option watchKey , which is the key we want to watch. Next, we use the useState hook to keep track of if this key is pressed or not. Notice, too, that we return pressed as the result of this hook. pressed is the primary value we're trying to extract, so that's what we return from the hook. So this gives us a hint to our implementation of handlePressStart -- what needs to happen there? We need to call setPressed to tell React that our key is pressed. Notice something here: we have to check to make sure the key that was pressed is the key we care about. Remember way back above that we said "keydown" will trigger for any key. So we have to filter our key code here. handlePressFinish is similar: Are we done? Not quite. We need to "clean up" after ourselves. Because React will re-render components, we need to make sure that if this component is re-rendered that we removeEventListener s that we created. We do this by returning a cleanup function from the useEffect hook: Putting it all together, we get this: It can look daunting altogether, but when you break it down it's not too bad. For the sake of space, I've had to leave a few bits of code out, but you can find the whole code example here on Codesandbox: So there you go! That's how you think about some native browser APIs in a React-y way. If you want to learn more about intermediate React patterns with TypeScript, check out Fullstack React with TypeScript:

Thumbnail Image of Tutorial Thinking in React Tutorial: a custom hook to capture keystrokes in TypeScript

A Simple Reducer Example with TypeScript, No Need for Redux or MobX

In this post, we'll cover React Reducers (with the useReducer hook). This tutorial will help you understand: By the way, this is an intermediate React topic. We cover this more in depth in Fullstack React with TypeScript . We just added a bunch of new content on how to use SSR with Next.js to the book. Check it out . As our React applications grow into full-fledged interactive apps - the amount of data -- and state -- they work with increases. Keeping track of state, and managing this state, creates a need for a layer of our app that deals solely with this important task. This is where reducers come in. All state management solutions perform some (or all) of these tasks: Reducers are a type of function that can perform these task for state management Because Reducers are built into the React API, you don't necessarily have to use a separate state-management library like Redux or MobX. Using reducer functions can lead to simpler code, as well as avoid the overhead of a separate state management library. Suppose that we're tracking the name of a person in our state. A reducer that manages this state must: Here is a diagram: We are going to create a restaurant order page that allows a diner to select a dish from several options on the menu. Make sure you have npm installed, then, to create our app, run npx create-react-app restaurant --template typescript . Our restaurant app will use React to display a menu to the user. When the user selects an item from the menu, we want to automatically change the state of the app to reflect the user's selection. To add a reducer, React provides us with a hook called useReducer . It works exactly as it sounds: React's useReducer is a function that allows us to specify the reducer we want to use, and the reducer will go into action to compute the new state of our application! At the very top of our App.tsx file, we import React and its useReducer hook using the line: To implement our reducer function, we must supply a state object and an action. The reducer will use this old state object and the dispatched action to figure out what the new state should be. It will then return a new state object for the application to use. Here is our reducer function that does exactly this: In this case, state is the old state we want to replace, and action is the action fired off from the user interface when a user selects a different menu item. TypeScript allows us to set types for both the state and action to mitigate against us making type errors in the code. If you look at the function definition above, you will see that our function arguments are accompanied by types. These types are defined briefly in the file src/App.tsx We've defined the reducer function above, but we need to actually assign it as the manager of our application's state. React provides the method useReducer(reducer) to enable us to select the reducer to use. Since our reducer is stored in a function with the name reducer , we can just assign it as the reducer for React to use with the call useReducer(reducer) . However, when we call useReducer , the useReducer hook returns a state and a dispatch method that will fire actions to change the state dynamically. So we need to store the returned state and the dispatch method. We do this with the following array destructuring assignment: Note: This useReducer assignment takes place inside our component. Check out the full component code here. Finally, we include logic to fire off actions to the reducer. These actions will be triggered by the user's interaction with the app. These actions are what lead to state changes in response to the user's selection of different menu items. Here's the code that fires off an action when the user selects from the available menu items. What this means is that, if a user selects a "pizza" from the menu, or a "burger", an action will be dispatched with that value as its type. This type is then assessed by the reducer, which takes the action and the old state of the app, then returns a new state for the app. React will then update the user interface automatically once the state has been changed by our reducer! And with that, you are ready to dive more into the code . Of course, if you want to learn how to use reducers with React, as well as testing with TypeScript, common best-practices and patterns, and using SSR with Next - then you should check out Fullstack React with TypeScript:

Thumbnail Image of Tutorial A Simple Reducer Example with TypeScript, No Need for Redux or MobX

Measuring Performance in Create React App

Create React App includes a built-in tool for measuring the real life performance of your app. It is called reportWebVitals and it measures a set of metrics that aim to capture the user experience of a web page. This set is called web vitals and includes: Under the hood Create React App uses a third-party library called web-vitals . To use this feature there is a function reportWebVitals , which takes another function as an argument. This argument function will be provided with an object of type: You can use beacons for better capturing performance reports on your analytics server:

How to Handle Keyboard Input Events in React TypeScript Application

When dealing with user interactions, you often need to handle some user events like mouse clicks, keyboard input, etc. Unlike with mouse events , TypeScript doesn't provide type declarations for an InputEvent . However, you can use KeyboardEvent for tracking keypresses: ... ChangeEvent for tracking input changes: ...and a basic SyntheticEvent for onInput event: As with the MouseEvent , you can pass a type parameter to either of those events: To create a general handler for input elements and textarea elements you can use unions as a type parameter: If you need to create your own event with additional fields you can extend it from KeyboardEvent , ChangeEvent :

How to Handle Mouse Events in React TypeScript Application

When dealing with user interactions, you often need to handle some user events like mouse clicks, keyboard input, etc. To handle mouse event in React you can use MouseEvent type to declare types on handler event argument: You can specify the element on which an event is being handled. It improves the type-safety and shrinks possible properties and methods to those that apply to a given element. If you want to create a handler that will handle events on buttons, links, and other elements, you can always use unions: If you need to create your own event with additional fields you can extend it from MouseEvent : And then use it as a type parameter of handled event.

How to create a React TypeScript application from scratch

Create a new project directory and navigate there: Init this directory as an npm -package. It will allow you to install third-party packages such as React and TypeScript later: Install React, React-DOM and TypeScript: Install type definitions for React and React-DOM. They will allow TypeScript compiler to work with packages and figure out the types that can and cannot be used with If you use some other packages you will need to install types for those packages too. The DefinitelyTyped repository contains the biggest amount of type declarations for npm packages. You can find the types for your package there and install them. Generate a tsconfig.json file using npx package runner: This file is used as settings for TypeScript compiler and tells it how to interpret the code. After it's done, open this file and add the following option: This will allow a compiler to work with JSX components as React components. Webpack is a static module bundler for modern JavaScript applications. It takes care of compiling, bundling and minifying the code for you. Install webpack , its command line interface, and html-webpack-plugin : The latter is used to deal with the html -entrypoint so that we will be able to run our application in a browser. The ts-loader package is a loader for webpack that knows how to work with TypeScript files. Webpack itself doesn't know that. Then, create a webpack.config.js file. Create an entry point file src/index.tsx : Create a first component src/components/App/index.tsx : Add a template src/index.html file: Install the webpack-dev-server package : This package is used to run application while developing. Also, it will reload the application when source code is changed. Set up development server in your webpack.config.js : In your package.json file, update scripts section with these scripts: The build script will build your application in a production mode which creates an optimized production build. And the dev script will set up a development server on localhost for you to develop the application. If you now run npm run dev and open http://localhost:9000/ you will see a running app.

How to a create class component using TypeScript

Create a new file with a component name, for example, Counter.tsx . Inside, create a class component as you would in plain React: Then, create a CounterProps type to define props that the component will accept and a CounterState type to type the state of a component if it has one. The CounterProps type is used to declare what type the properties of this component support. This is similar to declaring types with prop-types but without any additional packages and the result of type checking is available at design time. You won't need to run the project to figure out that some types are not correctly passed. The same with the CounterState type—it will check the state types at the pre-compile time, so you will know earlier if there is an error. You don't have to annotate CounterState the second time inside of a component itself, but it allows better type inference when accessing this.state . Notice the React.Component<CounterProps, CounterState> T type. This is the generic React.Component type. It takes two type-parameters that tell TypeScript how to interpret types of component props and state, so TypeScript can derive types of each field in props and the state. There is no need to mark types fields readonly since React.Component<P,S> already marks them as immutable. If your component doesn't need any state you can declare it without a state at all: Class Methods on a component are useful when you have to perform some action and want to extract its logic in a function. (In the example below, we log into a console the counter values.) You can define class methods as usual except for typing all of the arguments and return values: Class properties are useful for storing some data that should not affect re-render of a component. In the example below, it is a helloMessage that changes when a component is mounted. Its update won't trigger re-rendering. You can define class properties like plain TypeScript class properties with their type declarations:

How to add TypeScript to existing application built with Create React App

If you already have an app built with create-react-app , you can add TypeScript by installing it and type definitions for all the installed packages: Or if you use yarn : This command will add TypeScript to your project and provide type definitions for react , react-dom and jest —packages used in Create React App. If you have some other packages in your project, let's say enzyme you want to add types for those package too. The DefinitelyTyped repository contains the biggest amount of type declarations for npm packages. You can find the types for your package there and install them. Next, rename each component file to be a TypeScript file. For example: This will allow TypeScript compiler to work with those files. It is important to use .tsx extension for React-components in TypeScript to work properly. Now you can start the development server by running.

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

How to Define Props in React + TypeScript App

Props in React are like function arguments. They are passed in a component so it knows the data to work with. To define props create a new type where declare every prop that should be defined: The name for this type consists of 2 parts: It is now a good convention to name props types like this. To use a props type pass it as a type for components props: You also can use FunctionComponent and FC generic types for it: To define a props type with complex structures inside, it is better to decompose those structures in multiple different types. For example: You can use these types in component declaration as usual. You can declare optional props using ? : You can use an interface as well as a type for declaring props types: The difference between a type and an interface is in their extension. Let's say you want to extend ComponentProps with another field baz . In a case of a type you would write: In a case of an interface: On the contrary, an interface cannot extend a union type:

Thumbnail Image of Tutorial How to Define Props in React + TypeScript App

How to create a functional component using TypeScript

Create a new file with a component name, for example, Message.tsx . It is important to use the .tsx extension for the component to work properly. Inside, create a functional component as you would in plain React: Then, create a MessageProps type to define props that this component will accept. Use it to type passed props inside of a component: The MessageProps type is used to declare what type the properties of this component support. This is similar to declaring types with prop-types but without any additional packages and the result of type checking is available at design time. You won't need to run the project to figure out that some types are not correctly passed. Also, you can use React's FunctionComponent generic type to avoid typing props themselves and shorten the declaration a bit: This generic type will help TypeScript to derive props types. Similar, you can use FC generic, which is the same as FunctionComponent but shorter: Those generics support children prop. So, you don't have to manually define it in your component props if you need it.

How to Define Props with Children in React + TypeScript App

There are multiple ways to define props with children. You can declare children prop on your props type and assign the ReactNode type to it: If children should be optional, you can mark it with the ? : However, this is not very convenient to declare this field by hand every time. The PropsWithChildren type encapsulates children declaration in itself : You can use this type as a generic : The FunctionComponent generic interface includes children declaration. It uses PropsWithChildren under the hood. You can pass your props as a type parameter into this generic when declaring props: Another type you can use is React.FC . This is a type-alias for FunctionComponent , so it is the same as the previous one just shorter. When you declare a class component you can extend React.Component type: Like FC , the Component type automatically includes the children prop as well.

How to Install Types for Packages

When you develop an app you often use some third-party packages as dependencies. Not all of them are written in TypeScript, but many provide type declarations for a developer to be able to include those in a project. The biggest repository with type declarations is DefinitelyTyped . It contains type declarations for packages like React, Redux, Mobx, and many others. Some packages already have .d.ts files in them. These files contain type declarations. If your dependency package has it, you won't need to install types manually. If a package doesn't have .d.ts file and is written in plain JavaScript, you might need to find type declarations yourself. Let's say you want to use react-transition-group package. You installed the package itself and try to import it in a React + TS project: IDE will show an error that the project can't be compiled: A package may recommend installing types from a DefinitelyTyped or another repository in its documentation. If so, run all the commands recommended in docs. Otherwise, try to install types from DefinitelyTyped manually. In the case of react-transition-group : Usually, type declaration name consists of the @types/ prefix and the package name after it. (In some rare cases you may want to google the name first.) When types are installed IDE should hide the error and compile the project.

Thumbnail Image of Tutorial How to Install Types for Packages

wtf are Higher Order Components?

The Higher Order Component (HOC) pattern is used frequently in React libraries, so it's worth knowing. Below I'm going to show you what a HOC is, how to use one, and how to create your own.The Higher Order Component pattern reduces the amount of repetitive code you write as your app grows. A Higher Order Component provides common functionality that other components reuse. The Higher Order Component (HOC) pattern is used frequently in React libraries, so they're worth learning. When we talk about a “higher order” function, what does “order” even mean? Let’s look at a simple function first: Function  increment()  is a regular function that takes a  number  and returns the sum of this number and  1 . It is a normal, first-order function because it takes “normal” values as arguments and returns a normal value. A  higher order  function, is a function that either: (or both). Consider the following: Function  twice()  is a function that takes another  function  as an argument and returns a  function  as a result—that makes it a  higher order function . We’d use it like this: So the idea with a higher-order function is that we  generate a new function  that has  new abilities  based on the original function. Higher Order  Components  carry the same idea, but in the realm of React components. A Higher Order Component is a function that takes a  component  as an argument and returns another  component  as a result of some processing. Let’s see what a higher order component looks like in practice. First, look at this pseudocode of a higher order component. The higher order component takes a component, transforms it, and returns a new component. In code, that means we structure it like this: The result of applying  higherOrderComponent  to  SomeComponent  is the new component,  NewComponent . If you are struggling to wrap your head around how this works, remember our definition: A higher order component is a component/function that takes any component and returns another component - with modified functionality. For our next example, say we want to build a component to syntax highlight code in multiple languages - and support a dark mode. This is what our components look like: and These components print out code snippets ( codeSample ). Say, that we want to support a “night mode”, so that it’s easier to read at night. To keep it simple, all our “night mode” is going to do is add a  backgroundColor  of  wheat . This is what the component will look like: Our higher order component,  withNightMode , adds new styling with a slightly darker background by adding a  div  around  WrappedComponent . What is  WrappedComponent ?  Any component we want! We pass  WrappedComponent  in as an  argument  and  return a new component  as the result. Hence the term, “Higher Order Component”. Below, we use the component that is returned by our High Order Component function: You can try it out in this Code Sandbox 👆 In the code above, we use the higher order component  withNightMode  to transform our input components into versions that display with a “Night Mode” style. What’s cool is that we did not have to code this behavior in the components themselves. Rather, we made a higher order component that applies this behavior to any component we pass it. Of course, Higher Order Components can get more complicated. You definitely want to use  types  to ensure that your HOC and the components themselves are compatible. And we show some detailed examples of how to do that in  Fullstack React with TypeScript .

Thumbnail Image of Tutorial wtf are Higher Order Components?

Quick & Easy React Dropdown Component

In this post, we will discuss how to build a dropdown component in React. We will also add an animation to our dropdown.There are many approaches you can take when adding a component to your application, there is an abundance of component libraries you can use such as material-ui but sometimes it is better to just get your hands dirty and build your own one! In this post, we are going to do exactly that and build our own dropdown component. A dropdown is a staple in any web application and is most commonly used in menus to display a list of options to the user. A dropdown can also be used to display some information to the user that can be shown on a button click. They are used all across the web and you could also be asked to build one in your next interview! I know that building a component such as a dropdown may seem intimidating, but in this post, we will take it step by step so you can follow along. The knowledge gained from this post will also help you build any custom components! Ready? Let's go! By the end of this post, you will be able to: Armed with the above knowledge, you will have a newfound confidence when approaching building components in React. To get the most out of this article, we assume you're familiar with component basics in React, React Hooks, and also core JavaScript. If you do not know any of the above but would like to learn, here are some great resources: Now it's time to get started on our journey of building our very own dropdown component. Before building our dropdown component, it is important to discuss the different parts of a dropdown. There are four key components to a menu dropdown: Visually, we can imagine it like this: The component structure could look like this: The core functionality would be: The above is just theory, you can be as creative as you want when building your own component. When building custom components, it is really important to build the component to suit your use case as it may be quite different from the standard. It's good to use the best practice guidelines but also don't be afraid to be creative! Let's first start with a very basic dropdown, we will click on a button that will show a pop up that tells the user something. When building a basic dropdown component, there is one important piece of state. The important piece of state is whether the dropdown is open or not. We will also need to add a function to handle toggling this piece of state. This will all live in our wrapper component, which in our case is App . We can use useState to manage the showing and hiding of the dropdown for us (check out the docs here for React hooks ). We will pass both showDropdown and setShowdropdown as props to our component. Now we need to build our BasicDropdown component. The main thing we need is something to trigger our dropdown and also the content of our dropdown. We are using a button to trigger the dropdown and then we only show our content when showDropdown is true. There is a little CSS with this too, the key part of the CSS is setting position:relative on the dropdown-wrapper and position:absolute on the dropdown . We do this so that the dropdown will always be positioned to the the dropdown-wrapper . Visually, we now have: That is it, not too bad, eh? This is a very basic dropdown but still is very commonly used when displaying some information to a user. You could reuse this in various places and even expand it by opening it up to additional props such as a custom color or custom text. Why not try to add those additional props to the Codesandbox below, this will help further your knowledge of building custom components and making them reusable. So we can use a lot of the knowledge we gained above to help build our dynamic dropdown. The big difference with this dropdown is that it will accept a prop named items and it will also have a transition when it is being open/closed. The items prop will determine when it is rendered within our dropdown list. This could literally be anything. A very common scenario is sub-items for a navigation menu. In our case we are going to make up some items: We can then pass this into our dropdown component: Our dropdown component will behave quite similar to the one before, except we will map over each item in our array and create an li item. We will initially set our ul to have height 0 so that it is hidden. When showDropdown is true, we will set the height to 100px which will make it visible. To achieve this, we will use the following CSS (nothing too fancy going on, mostly overriding default browser styles): As you can see from above, we have set a transition on our height so that when the height changes it will do it with an ease transition which will last 300ms . You don't need to always use the animation property. In simple cases where only one attribute is changing in a predictable manner, we can use transition . Visually, we now have this: One important part to note is the overflow:auto . As we get a lot of items being passed to our list, we can then scroll our dropdown to suit this. Complete sandbox. Today we learned: If you're interested in learning further, try to build your own components. There are some great long-form articles you can read on building your own components such as this one . Personally, I would say that if you have read all the above then you should just open your own Codesandbox and start building components such as an Alert or a Modal. This is truly the best way to learn! Have a great day and happy coding.

Thumbnail Image of Tutorial Quick & Easy React Dropdown Component

Deploying Next.js Application on Vercel, Heroku, and a Custom Static Server

In this post, we will be looking at Next.js app deployment on different types of servers and using different technologies, such as: We will go through deployment setup on each technology step by step and show the code. Some time ago web-developers shipped their applications in production by hand. They might use FTP or some other protocols to copy built application assets to production server. This approach has a lot of downsides. Automatic deployment solves these problems by extracting the shipping process from development. Thus, it makes it possible to ship applications consistently, continually and automatically. Deployment in general is all the processes required to make an application available for use. In a case with a web-app typical deployment usually consists of building an app and uploading its assets to a server (production or staging). Deployment is automatic if all those actions happen without human interaction. So if a developer has to build an application themselves it’s not automatic deployment. Automatic deployment has many advantages: In our case, the deployment will consist of building an app and delivering its assets to a server. At the end of this post you will learn how to set up automatic deployments with Vercel, Heroku, and on your own server via SSH from your GitHub repo. We suppose you have a GitHub account—it will be needed throughout the whole post. We will use pull-requests as triggers to deployments. Also, we suppose you know what Next.js is and how to create applications using it. If you don’t know it yet, you can learn it from the 5th chapter of “Fullstack React with TypeScript” book and for this tutorial you can use our app starter pack . For the last section of this tutorial, we suppose you have a server with SSH access to it. You’re going to need one to be able to allow GitHub and GitHub Actions to upload app assets. Vercel is a solution for deploying applications built with Next.js from creators of Next.js. As it put in official Next.js documentation , it is “the easiest way to deploy Next.js to production”. Let’s try it. To connect Vercel and start deploying you’re going to need a GitHub repository. It will allow connecting Vercel to codebase and trigger deployment on new commits in the master branch. If you already have a repository with an application built with Next.js you can skip this section. Create a new repo at the  “New” page . If you don’t want to create a repository, you can fork ours with app starter files. Clone the project repository on your local machine and open the project. If the repository is empty, add application code, commit and push it. Vercel account allows you to connect your projects’ repositories and monitor deployments as well as see the deployment history. Create an account on the signup page . If you already have an account, you can skip this section. When you created an account you should have access to Vercel’s Dashboard . The dashboard is like a control panel. Here you will be able to see the last deployments of every application and recent activity of an imported project. Let’s import the project repo. Find the “Import project” button and hit it. You will be redirected to the “Import” page . On that page find the “Import Git Repository” section. Click ”Continue“ button in that section. You will see a form with an input that requires an URL of a git repository. Enter your project’s repository URL there and submit the form. When it’s done Vercel will redirect you to GitHub. There you will be asked by GitHub for permissions to repository. Allow Vercel read and write access to the selected repository. It is possible to allow third-party applications to read and write every repository you have, but not recommended by security reasons. Try to limit third-party application’s access as minimal as possible. After you grant permissions to Vercel, GitHub will redirect you back to the “Import” page. There you will see import settings: Keep the project name the same as the repository name to make it less ambiguous. The last two options may be useful if you have, for example, a custom build script. Let’s say, to build a project you use instead of standard npm run build some another command. In that case, you can override default command with your own in the “Build and Output Settings” section. Same with the “Environment variables”. Sometimes you might need to configure the build process from outside. Usually, it is done with environment variables that are passed via command line. The most often example is NODE_ENV variable, which configures what kind of build should be triggered. Its value set to production usually tells that this is a production build and should be optimized. In a case with Next.js application, we don’t need to configure anything except for a project name. When you set it up, hit the “Deploy” button. You will see the congratulations screen with a “Visit” link, which will lead to a freshly deployed app on vercel.app domain. Hit this link to open and inspect the current deployment. And that’s it! You just deployed an application and made it available for users! Now, return to the Dashboard for a minute. The new project will appear in a list of your imported applications. Click a link to your project. On a project page, you will see the ”Production Deployment“ section. It contains information about current production deployment, such as: Below, you should see a “Preview Deployments” section. This section contains non-production deployments, such as staging and testing deployments. Let’s say you want to test some features in the environment very close to production, but don’t want to ship an untested feature in production. Preview deployments will help you do that. By default to create a preview deployment, you need to create a pull-request (or merge-request) to default branch in your repository. Vercel will analyze the state of a repo and if there are some pull-requests to the default branch, it will deploy every new commit in this pull-request as preview deployment. To test it, create a new branch in the repository. Checkout to this branch on your local repo, make some changes in your code, commit and push them to the created branch. After that create a pull-request from a new branch to default. When it’s done, Vercel-bot will automatically deploy this pull-request as a preview and leave a comment right in pull-request. You won’t even need to return to the Dashboard to inspect your project, the link to preview will be in the bot’s comment! And of course, the preview deployment will appear in the list of preview deployments in Dashboard. Heroku is a container-based cloud platform for deploying and managing applications. It also allows you to automate deploys and trigger them by pushing to repository's default branch. The first step is basically the same as in the previous section. You’re going to need a GitHub repository. New commits in the master branch will trigger deployments on Heroku as well. If you already have a repository with an application built with Next.js you can skip this section. Create a new repo at the “New” page . If you don’t want to create a repository, you can fork ours with app starter files . Clone the project repository on your local machine and open the project. If the repository is empty, add application code, commit and push it. Heroku also allows you to monitor your connected apps and their activity. To connect Heroku with your GitHub repository you’re going to need a Heroku account. Go to the signup page and create an account. If you already have one, you can skip this section. When you have an account on Heroku, you should have access to its Dashboard . The Dashboard contains lists of all the connected apps and services. To create a new app find a “New” button and hit it. In a select chose “Create new app” option. It will redirect you to a page with the new app settings screen. There you will be able to choose a name for your app, and a region. The region can affect performance and download time. For example, for users in Europe app deployed to the US region might load a bit slower than for users in the US because of the distance a request should pass between a user and a server. When it’s done, add a new pipeline with the button below. A Heroku pipeline is a set of actions being performed over your application. Let’s say you want not to just deploy an app, but to test is first and only then deploy—this set of testing and deploying actions is a pipeline. Heroku Pipelines represent steps of the continuous delivery workflow. In this case you can select “Production” since we won’t run any tests and want to just deploy the application. After it’s done, you will be asked about the deployment method. There might be 3 options: The first one is convenient when you have a git repository and you want to deploy an app right from the command line . If you have a Heroku CLI installed, there is a special command for deploying from the command line: But since we’re using GitHub select the “Connect to GitHub” method. Then select a repository to connect to from a list below. You might be asked for repository permissions. Again, try to keep third-party app access as minimal as possible. When you grant permissions to Heroku you can set up automatic deploys for some branch. By default automatic deploys may be turned off, so don’t forget to check the checkbox in this section. When you turn them on, select a branch from which to deploy. By default it is master , but you can select any other branch in your repository. Optionally check “wait for CI to pass before deploy” to ensure your tests pass before a project goes to production if there are any. GitHub Actions are an automatization workflow for building, testing, deployment, and other routines. They allow you to create a custom life cycle for your app. So, you can setup code-linting, code-formatting, some code checks, and all. They are like robots that receive messages and do some stuff. Actions are being set up by YAML-files, that describe what to do and what triggers this action. To tell GitHub that there is an action that should be played, create a directory called .github , mind the dot in front of the title. This is the directory that contains all the actions and workflows for this repository. Inside of that directory create another one called workflows . A workflow is a set of actions. So if you want to chain some actions together in a list you can use a workflow. In workflows directory create a file called main.yml , this is the workflow. Open this file and paste this code inside: Let’s break it down. The first line describes the name of this workflow. When GitHub will run this workflow, in a workflow dashboard you will see a list of all created workflows. The next directive is on . It describes what events should trigger this workflow. In this case, workflow should be triggered on push event in the master branch of this repo. So when someone pushes to master branch this workflow will be played. For deployment with Heroku, there is an action called “Deploy to Heroku”. Open its page and scroll to the “Getting Started” section . There you will see an example of the workflow setup. Let’s examine it. jobs contains all the work to do. In this case, there is only one job to do— build . This job runs on ubuntu-latest , this is the type of a machine that runs a workflow. The steps directive describes what steps to perform. In the example, each step is a GitHub Action. Latter is being run with some arguments that are described with with directive. heroku_api_key should be generated and stored in the “Secrets” section in GitHub. For this, you’re going to need Heroku CLI. If you already have it installed you can skip this section. Heroku CLI makes it easy to create and manage your Heroku apps directly from the terminal. It allows you for example deploy right from your terminal. However in this case you need it for another reason. You need to generate heroku_api_key for the repository secrets section. This is done with Heroku CLI. To install Heroku CLI go to its page and select an OS that you use. Note that different OSs use different installation methods. When it’s done check if there are no errors by running: Then, authenticate with this command: You’ll be prompted to enter any key to go to your web browser to complete the login. The CLI will then log you in automatically. Thus, you will be authenticated in your terminal when you will use heroku CLI command. Notice YOUR_EMAIL in its response, this should be the same you set in heroku email of main.yml . To generate a new token open your terminal, check if Heroku CLI is installed and run As a response, you will get a generated token. Copy its value and create a new GitHub Secret with it. Go to the “Secrets” section in GitHub: Settings → Secrets → New Secret. Set HEROKU_API_KEY as a name and generated token as a value. Save this secret. GitHub will use this value and replace ${{secrets.HEROKU_API KEY}} with it at build time automatically. In your package.json update start script to be as an example below. Pay attention to $PORT environment variable, that must be specified . When it’s done you should be able to trigger deploys by pushing changes to the master branch. Try to update code and push to master . In Dashboard, you will see a new app in the list of apps. Click on it and you will be redirected to an “Overview” page. There you should see latest activity and all the settings for this project. Find the “Open App” button to visit your application and inspect it. Sometimes third-party solutions wouldn’t work. It might happen for many reasons: it can cost a lot, or due to security reasons, but it might happen. In this case, there is an option to deploy an application on your own server. In this section, we suppose you have a server with SSH access to it. It will be required later. The first step is basically the same as in the previous section. You’re going to need a GitHub repository. New commits in the master branch will trigger deploy. If you already have a repository with an application built with Next.js you can skip this section. Create a new repo at the  “New” page . If you don’t want to create a repository, you can fork ours with app starter files . Clone the project repository on your local machine and open project. If the repository is empty, add application code, commit and push it. You’re going to deploy an app via SSH. For this, there is an action called “ssh deploy” . It uses Node.js and integrates by YAML-file as other GitHub Action do. This GitHub Action deploys a specific directory from GITHUB_WORKSPACE to a folder on a server via rsync over ssh. This workspace is a directory that is created by checkout action we used before. The workflow will be: Let’s create a new file in .github/workflows directory called custom.yml . This is the file that will describe your new workflow. In this file write the name of the workflow and events that should trigger it. This code means that this workflow will be triggered on every new push in the master branch. The detailed explanation of every line of this code you can find in the section above. Then, describe jobs to do and steps. Here we tell GitHub to check out this code, it will create a workspace that can be accessed with GITHUB_WORKSPACE . The second action sets up Node.js with version 12. (LTS on the moment this post is being written.) Then describe build step: It will install all the dependencies, build the project, and export static files. next export allows you to export your app to static HTML , which can be run standalone without the need of a Node.js server. It works by prerendering all pages to HTML. The reason we use npx is because we didn’t install next CLI tools globally, so it won’t be found in GitHub Action runtime, which will cause an error. npx on the other hand will execute a local package's binary. The last step in the workflow is: It tells GitHub Actions to use ssh-deploy action and pass some of the environment variables: secrets. mean that the value will be requested in GitHub Secrets, and for this to work you're going to need to specify those secrets that should be stored in the “Secrets” section in your GitHub repository. Create 4 new secrets in your project. Go to the “Secrets” section in GitHub repository and create: Connect to your server via SSH. (You may be asked a password if you connect the first time.) When connected, generate a new key pair. Keep the passphrase empty. Specify the type of the key as RSA. You might want to set some unique name for the key, just to make it easier to find it later, so when a command-line ask you how to name the file, you can change it. When generated, authorize those keys, otherwise, the server might not allow “ssh-deploy” to connect. Note the ~/.ssh/key-name —that’s the full path to the key file. It may vary depending on your file structure on a server. Now copy the private key value and paste it as a value for SERVER_SSH_KEY in the “Secrets” section. When everything’s set, you can trigger new deploy. Push some changes to the master branch, and GitHub will run the workflow, which will build the app, export it and let ssh-deploy deploy it. In this post, we explained how to deploy your Next.js application using Vercel, Heroku, and how to deploy it on a custom server using SSH.

Thumbnail Image of Tutorial Deploying Next.js Application on Vercel, Heroku, and a Custom Static Server