Latest Tutorials

Learn about the latest technologies from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

The unused power of useEffect

In this post, we will discuss the useEffect hook offered to us by React Hooks which lets us perform side effects in function components.The release of React Hooks offered a new method of using React where we do not need class-based components. Before the introduction of React Hooks, all state was managed in class-based components. Function components were just used as dummy components i.e. just used to display data passed in by the use of props. Function components also offered no lifecycle methods, so knowing when the component had mounted or when it updated was very difficult and could only be handled in class-based components In addition to this, we also need some lifecycle method that would behave similarly to componentDidMount and componentDidUpdate , along came useEffect which gave us the power to handle side effects in function components. In React, there are two common side effects, side effects that require clean up and side effects that don't, useEffect can handle both of these side effects. By the end of this post, you will be able to: With the above knowledge in place, you will be able to build out an entire application with just function components. To get the most of this article, we assume you're familiar with the 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 let's get into it! We will first look at how we can implement useEffect into your application. The React team has made this quite simple for us. The interface for useEffect is quite simple, it accepts two arguments, a function, and an array: The first thing we need to do is import useEffect: Then we can use it in our component: Now let's look at the main points of useEffect : With all the theory we need in place, we will now look at an example in order to put our knowledge to use. It is very common to do an animation when a user sees your page, to do this we normally use a reference to the HTML element. In react, we use the useRef hook to achieve this: Then on your element: We then have reference to that element from the .current property of our sqaure ref. In our example, we want a square to be rotating when our page loads. We will be using the Greensock library for our animation as it keeps the animation code simple so we can focus on useEffect . So our component could look like this: The problem with this is that the .current property isn't available to us when the page loads. We will see the following error in the console: To remedy this issue, we can put the animation code inside of the useEffect function which won't fire until the component has loaded. Now our div will rotate when the component has loaded, if you have used React before then this is very similar to componentDidMount . The console will also have no errors. Here is a link to a Codesandbox that you can play around it: Updating the document is also another very common example of using useEffect . So if you had an array of names declared like so: We can store one of these names in state : We can add a button that onClick will pick a random name: So when this button is clicked we want to update a div that has the class of title . The code will look as follows: We want this to change every time that currentName is updated, we do this by adding the above like inside of useEffect . So every time our currentName changes, useEffect tells our component of what it needs to do when an update is performed i.e. in our case update the innerHTML . The is the pattern of useEffect , state updates --> run function . In our next example, we will look at changing this pattern. Here is the complete Codesandbox: Our final example is the most complicated but will help to even further our knowledge of useEffect . In this example, we will also be using the second argument that we can pass to useEffect . For our API, we are going to use the free PokeAPI . We can query this API with an id and it will return the Pokemon who belongs to that id , the id can be passed as a prop to the component. Finally, to fetch the data, we will be using axios . Our request will look like as follows: So above the ${id} part of our query string is the id that the user of the component will provide as a prop . When fetching data with React Hooks, you should place the code in useEffect so that the data will be fetched when the component mounts. You can do this like so: We declare some state initially where we can store our data, and then using the setter ( setData ) we can update state of our component. You will also see that I am using async and await which is handling the promise being resolved. If you were to run this code you would encounter a nasty bug, since we haven't supplied an array of dependencies (i.e. the second argument) we will get stuck in an infinite loop. Our component will mount, then update our state which will cause the useEffect function to fire again which will go through the entire process again and again and again...... How do we fix this? We supply an empty array to the second argument of useEffect . This second argument is to define all the variables that the hook depends on i.e. the variables it needs to watch for changes, in our case, it depends on none so this will stop useEffect running on component update. Great! So there is one last thing we have to deal with. The above code in Codesandbox gives the below error. It is telling us that the callback we pass to useEffect shouldn't be asynchronous and instead, we should place the asynchronous function inside of the callback. Thankfully, this is quite an easy fix. We need to create a function inside useEffect that will be our async function and then within that function we can make our request with await and set our state. Then we simply call that function within the useEffect block. Here is how it looks now: Great! That is how you fetch data with useEffect , not so bad right? Here is a Codesandbox that you can play around with: Today we learned: In addition to the above, we also learned how to use useEffect to manage that action we take when our component updates. We saw how useEffect can handle side effects in our components such as DOM manipulation and API requests. If you're interested in learning further, I really recommend checking out this long-form post by Dan Abramov . Have a great day.

Thumbnail Image of Tutorial The unused power of useEffect

Essential React Lifecycle Methods for Class Components

In this article, we'll look at three of the most used React lifecycle methods for class components - componentDidMount, componentDidUpdate and componentWillUnmount, and we'll briefly discuss their applications and alternatives. For each method, I'll give a practical example so that you can see it in action.React became open source in 2013 and it gained popularity quite quickly, which means that there are React applications out there that have been built as per the initial best practices. Yet, the framework has evolved a lot and multiple features have been deprecated. Among them, some of the lifecycle methods that we’ll talk about in this article. Until 2018 or so, classes with state built-in were the obvious choice for building stateful components. However, with the rise of functional components , hooks were also introduced, and thanks to their simplicity, they became the preferred solution for handling state. But those older applications that I mentioned were written with class components, and those class components were most likely using lifecycle methods for state management. Thus, if you’re going through the code base of your application and you see methods like componentDidMount or componentWillUnmount , know that these are called lifecycle methods. Today, they’re considered the last resort because of their complexity. However, if you’re already dealing with an application that uses these methods, it’s crucial to understand what they do and what to replace them with, if you want to refactor your codebase. This article should give you a clear understanding of how the lifecycle methods for React class components work, as well as what to replace them with if you decide they’re not a good fit for your application. This article explains what React component lifecycle methods are, so in order to get the most out of it, you should be familiar with the basics of React, and understand the difference between a class and a functional component. Also, you should understand the concept of state. If you’re not sure what these concepts are and how they work, please take some minutes to read React’s official intro to component types and our detailed guide to state . In a React application, the DOM is rendered only when a change happens. The components and their children are compared to the previous ones, and updates are applied only where the current state is different from the desired state. However, let’s say you have a page that displays pictures in a grid layout. New pictures are loaded as the user scrolls down, so new components are rendered into the DOM. You want to free up the resources taken by the components that are no longer needed when they disappear entirely from the page. The first rendering of the component in the DOM is called “ mounting ”, while the removal is called “ unmounting ”. Anything that happens in between, so from the “birth” (mounting) of the component to its “death” (unmounting) are state updates . The mounting, state update, and unmounting are the three lifecycle methods that we’ll look into in this article. To make this easier to understand, we’ll create a simple tagline class component and implement the methods one by one. Let’s get started! In class components, the only way to trigger code on state changes is through lifecycle methods. Because in the render() method you cannot use setState, if you need to change the state, you have to use componentDidMount() . This method is called as soon as the component is mounted, and it’s a good place to make API calls if you need to pull data from an endpoint. To illustrate this, let’s first create our basic class component. Right now this component displays the same heading every time we run the code: But what if we want to make this tagline dynamic, so that we can showcase multiple services? To change the state of this component, we need to call the componentDidMount() method, which looks like this: We’re delaying this state change by 2000ms, and calling the setState() method for defining the new state. The full component now looks like this: This renders first the tagline defined in the initial state: Then, after 2 seconds, the tagline component changes, and we see the heading defined in the componentDidMount() method: The re-rendering of our component happens before the browser updates the UI. This is extremely useful because we don’t want the user to see the UI updating weirdly. When componentDidUpdate() is called, it receives two arguments: prevProps and prevState . This method is called after componentDidMount() , and is useful when we want to change props or to perform some other action after the state change. For example, let’s say we want to change the color of the background when the tagline changes. In our previous example, we need to adjust the code a little. First, we’ll add a method that changes the color of the background: Then, we’ll add this property to the container of our tagline: We also need to add the background color in our initial state: Finally, we need to tell React that we want this color change to happen only after the tagline has changed, so only after the initial state was updated. For this, we’ll use the componentDidUpdate() method: With these changes, our code looks like this: If you run the code now, you should see first the light gray background with the initial tagline, and after the update, the second tagline with light blue background. Let’s imagine that this tagline is displayed in a hero banner component on the homepage. We want the user to see it when he first lands on the page, but we want further changes when the user moves to another page, or scrolls down. In this scenario, componentWillUnmount() comes into play. This method is called right before unmounting or destroying the component and is basically a cleanup action. By calling this method, you’re removing it from the DOM, so you can no longer re-render the component or modify its state. To illustrate this method, let's remove the tagline completely from the page when the user clicks a button. First, we need to adjust our app by adding the button, and at the same time, we'll wrap the tagline in a separate container, so that we still see the button when we unmount the text. Our updated code looks like this: That's a lot of code, so let's take it one by one, to understand the changes. First, we've split our main component, the Header, into two components: a <Tagline /> component, which is our previous class component, and a <button> element. We're storing the <Tagline /> in the header variable, defined with let. Since we want to remove if when we unmount the component, we've added an if condition: Also, we've defined our delTagline function, which unmounts the component: So now when we click the button, we're calling this function, which keeps the <button/> element on the page, but removes the <Tagline/> component. Our updated <Tagline/> component looks like this: You can see the full exercise here .  As previously said, these methods are only suitable for class components, so if you’re using functional components, you can replace all three with the useEffect() hook. You can read more about this in the React documentation . As you can see, lifecycle methods in class components have a more complex syntax than the hooks used in functional components.  If you’re just starting to build an application in React, you should opt for a simpler syntax. However, if you’re dealing with an older code base that includes lifecycle methods, it’s useful to know how these methods work.  If you want to learn more about React lifecycle methods, the following resources might be helpful:  I hope this was clear and useful! 

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

Bye bye, entryComponents?

In this blog post, we will look into what are entryComponents, why is the purpose of entryComponents, why do we no longer need to use them after Angular Ivy.With angular 9, there has been a lot of talking going on around entryComponents, and the Angular developers who had not been much aware of entryComponents have now been interested in knowing more about it. In this blog post, I will try to cover everything that might help you clear up all the thoughts you have around the usage, importance, and the goodbye of entryComponents . The best way to start understanding what entryComponents are would be by first trying to understand component renders in Angular and how really does the compiler play a role here. So just for a visual understanding of what we are talking right now, I have added below a snapshot of the component declarations inside the root module. Basically, there are two types of component declarations, ones which are included as a reference insides templates, and the other ones which are loaded imperatively. When we reference the component inside templates using the component selector, that’s the declarative way of writing components. Something like this: Now, the browser doesn’t really understand what app-instruction-card means, and therefore compiling it down to what browser would be able to understand is exactly the Angular compiler’s job. The imperatively written template for, for example, app-instruction-card would look something like this: This creates an element with your component name and registers it with the browser. It also checks for change detection by comparing the old Value with the current value and updates the view accordingly. We write templates declaratively since the Angular compiler does this rendering bit for us. Now, this is where we we can introduce ourselves to what entryComponents are! Before Ivy, Angular would create Ngfactories for all the components declared in the template and as per the NgModule configuration. During the runtime it would enable tree shaking for the components not used. This is why the dynamic components with no Ngfactories could not be rendered and would throw an error like: Adding the component to the entryComponents array would then make the factories for these dynamic components available at runtime. How Angular specifies a component as an entryComponent behind the hood can be in different ways. Using ngDoBootstrap() and using the same imperative code to declare a component bootstraps it and makes it an entry component into the browser. Now, you’d be wondering that if entryComponents have such a massive role to play in component declaration, why do we as developers see it rarely used?  As we discussed above, entryComponents are mostly specified in two ways, bootstrapping them or defining them in a router definition. But since these happen under the hood, we hardly notice it. However, when working with dynamic components, or web components in Angular, we explicity define the components as entry Components inside the entryComponents array. Inside @ NgModule , we can define the component inside this array: Alright, think for a minute. When we declare multiple components inside the declarations array of our modules, does that mean all these components will be included inside the final bundle? This is where entryComponents have a role to play. So the answer first of all to the above question is NO. All declared components aren’t necessarily present in the final produced bundle. It is if they are specified as entryComponents what decides if they’d be present in the produced bundle. This basically means that all the routable components will be present in the bundle for sure and also the bootstrap component obviously. This would also include the bundles that are declared inside the templates of other components. However, the tree shaking process will get rid of all the unused components with no reference without having to include them inside the package. EntryComponents are mostly explicity defined when dealing with dynamic components, like I said before. This is because there needs to be a reference for the compiler to understand that THOUGH , there is no reference for a particular component in the template or router for now, there is a possibility for it to be rendered dynamically when required. The ComponentFactoryResolver takes care of creating this dynamic component for us but we specify this inside the entryComponents array inside NgModule. If you have worked with dynamic components before, you might have faced an error like: Now knowing why need entryComponents, lets discuss a scenario where in we have created a dynamic component and have added it to the entryComponents array. This basically means that now since we explicitly declared it as an entryComponent, the tree shaker would not prune this component thinking that it doesn’t have a reference in the template. Also, specifying it as an entryComponent would create a component factory for this dynamic component. First, the entryComponent for a particular dynamic component could be added automatically whenever a dynamic component was created to be used. So this would save the developer from specifying it everytime to make sure the compiler knows the component. One more issue with using entry component was referencing the entryComponents declared inside a lazily loaded module. So if a lazy loaded module contains a modal component as an entry component, you’d face an error like No component factory found for this component. This was because the root injector couldn’t be referenced to create a component factory for the entryComponent. One solution, though not very promising was creating a component resolver factory yourself for a particular entry component inside the lazy loaded module to be able to execute it. With Angular 9 coming in and Ivy as the new rendering engine , all the components would be considered as entering components and do not necessarily need to specified inside the entryComponents array. With Ivy, the components will have locality and this means that dynamically importing these dynamic components will always work regardless of presence of entryComponents or ANALYSE _FOR _ ENTRY_COMPONENTS. This is because NOW, the presence of the @Component decorator would mean that the factories would be generated for this component and this happens due to the ngtsc compiler which is like a set of TypeScript transformers and these transformers introduce the static properties θcmp and θfac . These static properties are then able to easily access the code required for instantiating a component/module etc. See the update from the Angular official documentation here: https://next.angular.io/guide/deprecations#entrycomponents-and-analyz for entry_components-no-longer-required A demo here shows how entryComponents are no longer required with Angular 9 https://ng-run.com/edit/c8U6CpMLbfGBDr86PUI0 In this blog post, we talked about the need of entryComponents array when dealing with dynamic components or web components before Ivy . However after Ivy , we do not need NgFactories for the components by specifying it in the entryComponents array and the presence of Component decorator provides the code required for the instantiation of the components ensuring that the compiler is aware of the presence of these dynamic/web components .

Thumbnail Image of Tutorial Bye bye, entryComponents?

Mastering React PropTypes

In this post, we will be discussing PropTypes in React and how we can make our components more secure.JavaScript by nature is a loosely typed language , meaning it does not have any types such as string, integer, boolean, etc. This can become a challenge at times as users of our components may pass the wrong types to our props i.e. giving a string when we expect a number. We can use Typescript to help manage this but it requires quite a bit of a refactor to your application along with a learning curve. PropTypes may not be as powerful but certainly helps secure our application in a much shorter time frame. Overall, PropTypes gives us the ability to inform users when they pass something to our component that was not intended. From my own experience, when using reusable components, I always found it great when a component had it's PropTypes declared as it acted like documentation on how that component should be used. I am also much more confident in using a component that has it's PropTypes declared. By the end of this post, you will be able to: With the above knowledge in place, you will be more confident in building a component that will be used as intended. To get the most of this article, we assume you're familiar with the component basics in React (functional and class-based components) and also core JavaScript. If you do not know any of the above but would like to learn, here are some great resources: Now let's get into it! So, as mentioned above we use the prop-types NPM module to validate our props. You can install using yarn or npm . To access within your component we can import: You can now use PropTypes in all of your components: ( ComponentName being the name of your component) This is the same in functional components as it is in class-based components. Class based components aren't used as much these days due to the introduction of react hooks and letting us manage state in functional components. It is best practice now to keep all of your components functional, but in most react applications there will be a combination of functional component and also class-based components. Take the following Profile component that will display the age and name of a user. We want to make sure that the name prop is a string and the age prop is a number . It's actually not too complicated, we just need to add the following to our class component. Let's see what happens if we try to pass a number in for our name prop: It will display the name as 50 , but will show the following in the console. We can also tell our Profile component that name is a required field like o.. If we do the following: Our console will show: We have declared that our age prop must be a number, but age, as we all know, can be a sensitive subject so we can set age to have a default of 21 using defaultProps . Our Profile component is now much more secure and tells our users when they pass in the wrong value or the wrong value type to our component. Here is a Codesandbox that you can play around it: When creating functional components, you will also want to validate the props being passed in to make your component secure. Let's turn our Profile class component into a functional one. Thankfully, that is the biggest change we have to make. Like above, we can do the following: Here is a Codesandbox that you can play around it: PropTypes also support renderable props. Take the following Paragraph component, that has a children prop. We want to ensure that our component has only a single child. Our PropType would then look like: If we tried creating this component like so: We would get an error in our console informing us that we expect a single element. This is a common pattern and if you have ever used a component library you've probably seen it before. Here is the Codesandbox: PropTypes also has a oneOf property that ensures your prop is limited to specific values using an enum. Take the following Alert component: This component accepts a type prop which determines the type of warning. We have three types for our warning so we can use the oneOf property to tell the user if they pass in something we don't expect. Since banana is not one of our values, an error will be shown in the console. This is quite powerful and allows us to build resilient components. Here is the Codesandbox: PropTypes.shape is another validator we have at our disposal that we can use to validate objects being passed into our component props. Take the following Profile component that accepts a person object: So we can give the user an error if their object does not have a name or age prop. Here is a Codesandbox: PropTypes also lets us create custom validators using something like regex . If our component accepts an email prop, we can add a custom validator for it. We can do this like so: We can include the custom validator in the shape property. If an invalid email is passed in we give a custom error message which in our case is Invalid email address . In the console this looks like: Here is the Codesandbox: We have covered most of the available validators above but here is a list with all of them. Today we learned: If you're interested in learning further, the React docs have a great section on all the different PropTypes we have. Have a great day.

Thumbnail Image of Tutorial Mastering React PropTypes

The Ultimate Guide to Storybook for React Applications - PART II

In Part I of this guide, I've covered the basics of Storybook and explained what this tool is, what it does and how it's used by product teams. Now that we know the theory, we can see how Storybook works in practice by building a small application. This article is part of the Ultimate Guide to Storybook for React Applications . If you'd like to get an overview first and understand what Storybook is, what it does and how to add it to your project, please read Part I of the guide first. A design system is an independent component library that serves all the applications within an organization. It’s not only a collection of UI building blocks or of page templates; a design system comes with standards that guide the use of the components and ensure consistency across applications. Here are some examples of design systems: In this tutorial we will be building the following blocks: We’ll apply atomic design principles, meaning that we’ll build our UI library as a collection of components that are the smallest building blocks, and can be assembled into compositions or composite components. Thus, with the building blocks from above and with some utilities for consistency, we’ll assemble a hero banner. If you clone or download the repository, you'll see the following project structure: In the .storybook folder, we only have the main.js file for configuration. In the public folder, we have all the assets needed for this project. Finally, in the src folder we have the following files: In the components folder we have all the components in separate folders, each of them containing 3 files: To be able to use React and Storybook, you need to have Node.js installed as well. So open your IDE and in the terminal, type: If you don’t have Node installed yet, go to the download page and get the version that applies to your operating system. Alternatively, you can install Node with a package manager. In this page , you’ll find instructions for the different operating systems. Node.js comes with npm , which is a package manager. We will use npm for installing all the other tools and dependencies in this guide. Let’s start by installing React. We will use a boilerplate to get up and running a bit faster, so if you’re not familiar with what a boilerplate or starter kit it, please take a few minutes and look at the Create React app repository . To initiate a new React project, create a new folder with your desired project name and open it in your IDE. I will create the new project in a directory called react-storybook , so I’ll open this folder in VSCode. To be able to use npm inside this folder, we first need to initiate it, so in the terminal, run this command: You should see the following screen, which asks you to confirm some configurations for creating the package.json file. Accept the default ones by pressing Enter. Once you’re done with this, you should see that a new file called package.json was added to your project folder. For now, because we’ve accepted the default setup, there’s not much going on. However, you’ll see that once we start installing libraries and dependencies, this file will be automatically updated. So let’s go ahead and initiate the React application. To do so, run this command in the terminal: If we check now the package.json file inside the react-project folder, we see a couple of development dependencies, as well as a few scripts: Now if we want to launch the React application, all we have to do is run this command in the terminal: If everything was installed correctly, you should see a new window open in your browser at localhost:3000 , with the React application: Let’s move to installing Storybook. In the react-project folder, run this command: Let’s see if the installation was successful. In the terminal, type: This should open Storybook on port 9009, so you should see a new window open in your browser. When you installed Storybook, a new file called main.js was added to your .storybook folder. Let’s take a look at what’s inside it. This file looks in all src/** folders and searches for story files that have the .stories.js extension. These stories are then rendered in the Storybook application. Here's a practical example. In your src/stories folder, there is a file called 0-Welcome.stories.js , with the following code: We see that this file is by default exporting a component called Welcome. If you look in the Storybook application, we can indeed see such a component: What Storybook says is that a story is a single state of a UI component. So if we look here, we see that under the Welcome component, we have one story, or one state, called to Storybook . Let’s go back to the actual code and see if we can identify the story inside the component. The <Welcome /> component is indeed exporting one story, called ToStorybook . This story is added to the application by the last lines in the code above. Let’s change the name of this story and call it “ to the Storybook application ”, to see if it works correctly. Now that both React and Storybook are installed and working properly, there’s one more step to go through before creating our first real component, and that’s installing some dependencies. Because we’re using the create-react-app (CRA) boilerplate, most dependencies - such as Babel for transpiling JSX to JS, or Webpack for bundling the JS files - are already installed. However, we will install one new library, so that we can write our styles faster: Styled Components . In your terminal, run this command: In the next step, we’ll create the first component of our design system. We’ll build the component in React with Styled Components, and we’ll render it in Storybook, so see how they work together. In this section we’ll build a title and a button component, to see how React and Storybook communicate, and how props and states are passed. Let’s go to our project folder, and under src/components , and add a new folder called title. In this folder, create two new files: Title.js and Title.stories.js . In the Title.js file, we’ll build our React component. Copy this code into the file: To render the component in our React application, we need to adjust the App.js file from the react-project folder. Now if you refresh the page at localhost:3000, you should see this component: If it doesn’t work, make sure you’re in the correct folder, and run again in the terminal the command npm start . Now that we have a Title component, let’s add it to our UI library in Storybook. To do this, you’ll need to add this code to the Title.stories.js file: If we check Storybook, the Title component with the first state or story - called “default” - should be visible: Let’s create another style for the title, for dark backgrounds. We’ll call this story “reverse”, and we’ll make use of Styled Components. For this, you first need to create a file called style.js in the src/title folder, and add the following code: If we want this style to reflect in our Title component, we need to adjust the JSX code a little, so in your Title.js file, make the following changes: What changed here? Instead of returning a plain <h1> in the Title() function, we’re now returning a styled <h1> , which was defined in the style.js file and exported as the <Heading1> styled component. So let’s see if these changes are reflected in our React app and in Storybook. We see that indeed the Title is now light blue, but if we inspect this component, we notice that a random class name was attached to it. This is Styled Components in action. What this library does is to assign unique, random class names to the components, in order to keep a local scope. Our component is now by default light blue, but we actually wanted this to be a variation for dark backgrounds, and not the default state. So in the Title.stories.js file, let’s add a new story and call it Reverse . Props is basically an object that is passed to the JS function and contains key-value data pairs; in our case, the props object contains a key called “reverse”, but what’s the value? If we inspect the stories added to Storybook, we see that both Default and Reverse are light blue: We therefore need to find a way to tell React and Storybook that we want this title to be light blue only when we pass it the “reverse” property. How do we do this? In the style.js file, we need to add a condition that binds the light blue color to the “reverse” property. Here’s how the code looks like: As you can see, our Heading1 styled component can now have 2 color variations: when the component receives the “reverse” props, it will be light blue. And when it doesn’t, the styled <h1> will be black. Let’s see if this works correctly in Storybook: Title default is indeed black, and Title reverse is light blue. Now let’s adjust our React component also, so that when we add it to the application, it behaves correctly. We need to change the code in the Title.js file a bit: As you can see, we’re now passing the {reverse} variable as a property to the Title function, and we’re telling React that the appearance of <Heading1> is dependent on the variable {reverse} . This is how a basic component is built in React and rendered in Storybook. At this point, you should see already how valuable this UI environment is! Without Storybook, if you wanted to see the different states of this component, you would have to first pass a prop to the title component, then remove it, and re-render the component in React. With Storybook, there’s no need to alter your application. You can see both titles with their respective colors in an isolated environment, and you can easily adjust them by passing or removing props in the Title.stories.js file. Let’s adjust also the button components that are already in Storybook, before we move to the next step. In the src/components folder, I’ve added a new folder called button, and inside it, 3 files : Button.js for the React component, Button.stories.js for the Storybook stories (button states), and style.js for the Styled Component. First, we’ll create the styled button in style.js . Whenever you create a new styled component, you need to add at the top of the file this line: Also, at the end of the file, after defining your styling, you need to export the component: Here’s the full code for the styled button: Until now we only have styling defined. To render this component in our React application, we need to build the Button.js code: Then, we need to add the button to our application, in the App.js file: If we now refresh the React application, it should render this: That looks quite ugly, so let’s get rid of the dark background and style the button a bit more. To remove the background, we need to see where it’s coming from. If we check the App.js file, we see that we’re importing some styling from App.css . In App.css , I’ll remove the color and background properties from the .App-header class. Then, in the components/button/style.js file, I’ll adjust the code as follows: One more step, before moving on to the next part of this tutorial: let’s add the button to Storybook, and get rid of the default ones. First, I’ll delete the stories folder, as we no longer need the demo stories. Then, in the Button.stories.js file, I’ll add the following code: If we switch to Storybook, we see now the Button component and its Primary state rendered: In the next section of this tutorial, we’ll define our utilities to maintain consistency across the project, and we’ll create the author box and banner. But before doing so, let’s initiate git in this project, and create a GitHub repository, to make sure we don’t lose all the work. If you aren’t sure how to do this, please follow the steps in this tutorial, it shouldn’t take more than 10 minutes: IDE and Git for self-taught front end developers . You can access the repository here . Earlier in this article I’ve mentioned that Storybook helps to maintain consistency in design, but we aren’t taking advantage of this yet. So in order to make sure we’re not deviating from our brand guidelines, let’s build our utilities. To define the color scheme, I’ll use the Eva Design System . I’ve picked the following colors: To keep it simple, we’ll choose the #100 and #800 values for backgrounds, and the #500 values for components. Also, we’ll use two shades of grey as support colors. To build the color scheme, create a new file called utilities.js in the src/ folder and add this code: Now let’s go back to our Title and Button components and adjust their colors. Under style.js for title , change the code as follows: Then, under style.js for button , change the code as follows: Our components now look like this: Let’s switch to Storybook and add 2 variations for the button: a success and a danger one. In style.js , add the following: Then, in Button.js , adjust the code as follows: Finally, add the variations to Storybook by adjusting the Button.stories.js file: Our buttons aren’t interactive yet, so before moving on to assembling the Hero banner, let’s add some styling for the hover state: Do the same for the success and danger buttons, keeping their color schemes: We forgot one thing. If you check the Title component in Storybook, you’ll see that the default one is blue, but the reverse one is white, so on a white background, we aren’t able to see it. However, we don’t want to alter our component just to be able to see it correctly in the UI library. This is a scenario where decorators are useful. In your Title.stories.js file, import the background colors: Then add a decorator to the Reverse story: If we check the titles now in Storybook, we see that the reverse one has a background: In order to assemble our Hero banner, we need the building blocks ready. Until now, we only prepared the title and button, but we also need an image as background and a wrapper to hold all these components. Let’s first create our folder under src/components , and call it heroBanner. Inside it, create the 3 files: We start by styling a wrapper: Now, we’ll build the HeroBanner component: And finally, we’ll add the story to Storybook: Here’s how our banner looks: Let’s implement it in our React application as well. To do so, we’ll adjust the code in the App.js file: Now we have a composite component, but it’s static, so we can improve it with data and addons. If we click on the button, nothing happens at the moment, so how do we know if this component behaves correctly once integrated in our application? Addons are useful in this scenario. In our Button.stories.js file, let import the action addon from Storybook: Next, we need to add an event on the Button component: Let’s switch to Storybook and see what happens. If you press the button, you should see in the Actions panel at the bottom the ‘button clicked’ message registered. But it doesn’t happen yet, and that’s because we forgot to pass the event handler to the actual button component. So in the Button.js file, let’s adjust our StyledButton: Now if you click the default button story, you should see this: What if we want our HeroBanner to be a bit nicer and have an actual image as background? Then we need to tell Storybook where to find the assets. To do this, we have mention the folder in package.json , under scripts: I will be using this photo from by Mikhail Vasilyev on Unsplash , which is located in the public folder. In the style.js file of HeroBanner, I’ve added a styled <img> : Then, I imported it in the HeroBanner.js component: And I’ve exported it with the property src, so that we can pass in Storybook the image. In HeroBanner.stories.js , I’ve added the following code: So if we check now the banner in Storybook, it looks like this: Since we’re here, let’s add one more addon. Run this command in the terminal: Let’s see what this addon does. In your HeroBanner.stories.js file, import the addon at the top, and export it with the image header: If you check the image banner now, you’ll see a Show Info button. Click it and you’ll see the source code and properties of this component. Finally, let’s make use of the Knobs addon also. In your Button.stories.js component, import the addon at the top, and export it as decorator for the default button: Then, in your Button.js file, add a {children} parameter, so that whatever text we add on the button, it’s displayed: If we now check the Button component in Storybook, we see it as follows: The Knobs tab at the bottom allows us to easily customize the text on the button, without having to change the code. I’ve updated the code for all the components to include knobs, so before going through this step, please get the latest version of the code here. To see how Storybook handles state, we’ll try to convert our image banner into a slider. I’ll be using these 3 images, which will be added to the public/ folder: Let’s start by adding these images in a state array, inside the HeroBanner image component: Now if we check the image banner, we see that the second picture is rendered: I’ll add a button to turn this into a slider: Then, we need to import the button into the component, and to render it: The next step is to add an onClick event on this button, so that whenever we click it, we see the next picture in the slider. We’ll do this by incrementing the index, so let’s create a new function called handleIndex , and pass it to the button: We’ve added a const[index, handleIndex] = useState , which is a React hook that enables us to add state to our component. If we now check our slider in Storybook, and click the two buttons, we see that we go to the previous and next image. Next image: And previous: In this step we've added a new button, but we've created the style for it inside the Hero Banner component. This is bad practice, as we said we'll keep all the stories related to buttons in the dedicated component. So go ahead and move it in the style.js file in the button/ folder. Also, rename it to ButtonBullet, as it's not really a pagination button. Storybook can be easily integrated with testing tools such as Jest, Enzyme, BackstopJS or Chromatic, for performing visual, snapshot, unit and regression tests. Visual testing means checking if the components look correctly, snapshot tests check if the components' rendered markup is correct, and unit tests verify the functionality of a component. All these methods are good, but they're not complete without regression tests, which help identify changes in components' appearance from one code commit to another. Storybook provides an addon called for StoryShots which adds automatic Jest snapshot testing to the project. So let's see how this works. First, we need to install the addon and a React dependency, so run these commands in the terminal: Then, in your src/ folder, create a new filed called Storyshots.test.js . In this file, add the following code: You're now ready to run your first snapshot test. Use this command: You should see something like this in the terminal: Now let's change something in one of the components. In the Title component, I'll change the decorator that stores the background color. As soon as I save the change, the test runs again, and this time I get an error: We know that this test failed because the snapshot no longer matches the component, so let's press 'u' to update the snapshots. Now if we run the tests again, they should be successful: You can find detailed instructions for running all the mentioned test types here . To deploy our application, we'll use GitHub Pages. Install this dependency by running the following command in the terminal: Next, in package.json , add a new line to mention the homepage where you want to publish your application. Add this line under "private". Then, under scripts in the same file, add two new scripts: The last step is to run the npm run deploy command in the terminal, and your application will be deployed to the homepage that you indicated. The application built in this tutorial can be accessed here . Feel free to clone the repository of this project and to experiment with the components. Storybook makes it easy to develop a living styleguide or UI library that not only displays your components, but it also enables interactions and testing, assembling the blocks into composite components and deploying the application. To learn more about Storybook and its functionalities, check out these websites:

Thumbnail Image of Tutorial The Ultimate Guide to Storybook for React Applications - PART II